Hello,
I have a coding related issue with my project. It is a speedometer using a reed switch, converting measured blinks from a driveshaft on a tractor to MPH at the wheels. The issue is is that when i go to serial monitor to display information during testing, I get values of 0.00. Here is the code:
#define reed A0
int reedVal;
long timer;
float mph;
float radius = 12;
float circumference;
float gearing = 3.83;int maxReedCounter = 100;
int reedCounter;void setup(){
reedCounter = maxReedCounter;
circumference = 23.14radius;
pinMode(reed, INPUT);//Setup Timer, allows for precise timed readings of the reed switch
cli();//breaks interrupt//set interrupt to 1kHz
//TCCR variables are to set up timers, Google them.
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A = 1999; // = (1/1000)/((1/(16*10^6))*8)-1
//CTC mode TURN ON
TCCR1B |= (1 << WGM12);
//timer compare interrupt
TIMSK1 |= (1 << OCIE1A);sei();//interruption allowance
//END TIMERSerial.begin(9600);//bauds
}ISR(TIMER1_COMPA_vect){//interrupt @ freq of 1kHz to measure reed
reedVal = digitalRead(reed);//obtain val from pin A0
if (reedVal){//when reed closed
if(reedCounter == 0){
mph = (56.8*float(circumference))/(float(timer)*float(gearing));
timer =0;//timer reset
reedCounter = maxReedCounter;
}
else{
if(reedCounter > 0){
reedCounter -= 1;
}
}
}
else{
if(reedCounter > 0){
reedCounter -= 1;
}
}
if(timer > 2000){
mph =0;
}
else{
timer += 1;
}
}void displayMPH(){
Serial.println(mph);
}void loop(){
//once a second mph display, can be adjusted
displayMPH();
delay(333);//milliseconds
}
I know it's not a mechanical issue because i used this for test and it displays '1023' when a magnet is near the reed switch:
#define reed A0
int reedVal;
void setup() {
Serial.begin(9600); //enabling 9600 baud for serial monitoring
}void loop() {
reedVal=analogRead(reed);
Serial.println(reedVal);
delay(10); //assign refresh rate to 10ms
}
I am a newer programmer and self educated, so help with this issue and advice is greatly appreciated. This is a modified version of the famous arduino bike speedometer.