So, I've changed the relevant terms to floats - and now, the code works as expected. Great! See the code below. Thank you for all help offered thus far!
// program will run for 70 minutes until currentmicro overflows
// check what will happen at overflow time
// changed millis to micro, thought of floating point, but too slow
// attempt change back to milli
volatile int timer_pulsecount = 0;
volatile int angle_pulsecount = 0;
float timer_c_pulsemillis = 0;
float timer_p_pulsemillis = 0;
float threepulsetime = 0;
float threepulsetimecopy = 0;
int rpm = 0;
int tooth_spacing = 10;
int lastCommand = 0;
float dpm = 0;
unsigned long debug_p_millis = 0;
unsigned long debug_c_millis = 0;
void setup()
{
Serial.begin(9600);
attachInterrupt(0, crank, RISING); // din D2
}
void crank()
{
timer_pulsecount++; //
}
void loop()
{
////////////////// SPEED AND POSITION TRACKING ///////////////////
timer_c_pulsemillis = millis();
dpm = 3 * tooth_spacing / threepulsetimecopy; // causing problem, due to multiplying diff types
rpm = (dpm * 60000) / 360; // converts degrees per micro to rpm
if (lastCommand != timer_pulsecount){
lastCommand = timer_pulsecount;
switch (lastCommand){
case 1:
timer_p_pulsemillis = timer_c_pulsemillis;
break;
case 3:
threepulsetime = timer_c_pulsemillis - timer_p_pulsemillis; // needs to be reset to 0
threepulsetimecopy = threepulsetime;
break;
}
}
if(timer_pulsecount > 3)
{
timer_pulsecount = 1;
threepulsetime = 0;
}
////////////////// DEBUGGING SERIAL STREAM ///////////////////
debug_c_millis = millis(); // starts counting currentMillis
if(debug_c_millis - debug_p_millis >= 500) // if current - 0 is > 1000, run if script
{
debug_p_millis = debug_c_millis; // set previous to current
Serial.println(timer_pulsecount);
Serial.println(tooth_spacing);
Serial.println(threepulsetimecopy);
Serial.println(dpm);
Serial.println(rpm);
Serial.println("");
}
}
// print the above data, timer_pulsecount increments correctly
// timer_p_pulsemicros is set to current when timer_pulsecount = 1
// previous and current pulsemicros latch as they should
// three pulse time saves on 3, resets when timer_pulsecount loops to 1
// current program WORKS!!!! One slight issue, if engine stalls, rpm will still be reported
I'm just about to have a play trying to get it to work using scaled up integer math as suggested. However, one issue I didn't anticipate... if interrupt pulses stop after the rpm calculation has been performed once, rpm will continue to output the last value until another 3 pulses are received and calculated.
Any ideas as to how I would create a piece of code that says something along the lines of the following?
if(no pulses are received in the next 100ms)
{
dpm = 0
}