Hello, I am currently working on a project motorcycle I have. It's an '82 Yamaha and the ignition module seems to be going out. I wanted to try to construct my own electronic ignition for it using an Arduino Mega 2560. It is a single cylinder bike so I have to read one pulse per revolution from the pickup coil, and from that I should be able to calculate the RPMs. The issue I am having is with the actual calculations, I think. The bike idles at 1200 rpm, but my calculations show about 55.0 at idle. The code I wrote is included below.
// Declare Variables
volatile int revolutions = 0;
int old_rpm[] = {0, 0, 0, 0};
int new_rpm = 0;
unsigned long old_time = 0;
unsigned long current_time = 0;
float average_rpm = 0;
////////////////////////////////////////////////////////////
void setup()
{
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(2), rpm_counter, RISING);
// Write pin 2 high for pullup.
digitalWrite(2, HIGH);
}
/////////////////////////////////////////////////////////////
void loop()
{
// Update rpm every XX number of revolutions.
if (revolutions >= 25)
{
// Detatch Interrupt while calculating
detachInterrupt(digitalPinToInterrupt(2));
// Update Current Time
current_time = millis();
// Calculate the new rpm
new_rpm = (revolutions * 1000 * 60) / (current_time - old_time);
// Save Current Time as old time for next calculation.
old_time = current_time;
// Calculate 5 point moving average, update old rpm readings.
average_rpm = (new_rpm + old_rpm[0] + old_rpm[1] + old_rpm[2] + old_rpm[3]) / 5;
// Update old_rpm with new_rpm, replacing last value of array.
old_rpm[3] = old_rpm[2];
old_rpm[2] = old_rpm[1];
old_rpm[1] = old_rpm[0];
old_rpm[0] = new_rpm;
// Print values for testing
Serial.println(average_rpm);
Serial.println(revolutions);
//Reset revolutions to 0.
revolutions = 0;
//Re-attatch interrupt
attachInterrupt(digitalPinToInterrupt(2), rpm_counter, RISING);
}
}
void rpm_counter()
{
// Update number of revolutions
++revolutions;
}
I can turn the engine by hand and increment 'revolutions', and when the value is printed, it always seems to be correct. But when I print 'rpm', which should be somewhere in the neighborhood of 1200, I only get about 55. My guess is that there is an issue with the way I am handling the time calculations but I'm not sure. I guess my main question is; how am I messing up the rpm calculation but counting the number of revolutions correctly? Any help would be appreciated, thank you!