Code:
/* draft of signal processor for the opengauge project, untested
sends the injector open time (in microseconds), the number of injector
pulses, and the number of vss tics out the serial port once a second.
*/
//overflow counter used by millis()
extern volatile unsigned long timer0_overflow_count;
//will reset after 71.5 minutes, so don't time anything longer than that
//about 4 microsecond resolution @ 16mhz
unsigned long microSeconds (void){
return ((timer0_overflow_count << 8) + TCNT0) * 4;
}
//return the elapsed microseconds, accounting for overflows
unsigned long elapsedMicroseconds(unsigned long startMicroSeconds ){
unsigned long msec = microSeconds();
if(msec >= startMicroSeconds)
return msec-startMicroSeconds;
return 4294967295 - (startMicroSeconds-msec);//someone check my work here
}
//use pins 2 and 3 because that is how the arduino is set up
//we use timer0 for ALL our event timing.
int injectorPin = 2; // connected to the injector signal
int vssPin = 3; // connected to the vss signal
int ledPin = 13; // display one second heartbeep
unsigned long injHiMS;
unsigned long injCount;
unsigned long vssCount;
unsigned long injHiStart;
void processInjChange(void){
detachInterrupt(0);
boolean injHI=digitalRead(injectorPin);
if(injHI){
injHiStart = microSeconds();
}else{
injHiMS += elapsedMicroseconds(injHiStart);
injCount++;
}
//really should re-attach the interrupt after the injector settle time
attachInterrupt(0, processInjChange, CHANGE);
}
void processvssHI(void){
vssCount++;
}
void setup (void){
Serial.begin(9600);
pinMode(injectorPin, INPUT);
pinMode(vssPin, INPUT);
attachInterrupt(0, processInjChange, CHANGE);
attachInterrupt(1, processvssHI, RISING);
}
unsigned long looptime=1000;
void loop (void){
unsigned long loopStart=millis();
digitalWrite(ledPin,HIGH); //heartbeat indicator
// buffer the values to send and reset them
unsigned long tmpInjHiMS = injHiMS;
injHiMS=0;
unsigned long tmpInjCount = injCount;
injCount=0;
unsigned long tmpvssCount = vssCount;
vssCount=0;
//send the values out the serial port.
//LCD display routines triggered here also
Serial.print(tmpInjHiMS, HEX);
Serial.print(",");
Serial.print(tmpInjCount, HEX);
Serial.print(",");
Serial.println(tmpvssCount, HEX);
//heartbeat indicator off.
//If the led is mostly on then way too much time is spent
//sending/displaying the data
digitalWrite(ledPin,LOW);
while (millis()-loopStart < looptime);
}