Hello, I have some codes for an arduino speedometer and I'm using a reed switch and a magnet. The reed switch is fine. I just don't understand what's wrong with the code because I already grabbed this code from a website and it should work and I've adjusted it to produce something on my LCD (MPH : 0.00) . The problem is that the LCD usually says mph 46.8 or it changes between this and some other speeds. I don't think it is measuring the times the magnet is passing through the magnet either that or the interrupt isn't working? Forgot to mention I'm using an LCD shield.
#include <LiquidCrystal.h>
#include <String.h>
//storage variables
float radius = 13.5;// tire radius (in inches)- CHANGE THIS FOR YOUR OWN BIKE
int reed = A1;//pin connected to read switch
int reedVal;
long timer = 0;// time between one full rotation (in ms)
float mph = 0.00;
float circumference;
boolean backlight;
int maxReedCounter = 100;//min time (in ms) of one rotation (for debouncing)
int reedCounter;
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
void setup(){
reedCounter = maxReedCounter;
circumference = 2*3.14*radius;
pinMode(A1, INPUT);
lcd.begin(16, 2); // start the library
cli();//stop interrupts
//set timer1 interrupt at 1kHz
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1 = 0;
// set timer count for 1khz increments
OCR1A = 1999;// = (1/1000) / ((1/(16*10^6))*8) - 1
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS11 bit for 8 prescaler
TCCR1B |= (1 << CS11);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei();//allow interrupts
//END TIMER SETUP
Serial.begin(9600);
}
ISR(TIMER1_COMPA_vect) {//Interrupt at freq of 1kHz to measure reed switch
reedVal = digitalRead(reed);//get val of A1
if (reedVal){//if reed switch is closed
if (reedCounter == 0){//min time between pulses has passed
mph = (56.8*float(circumference))/float(timer);//calculate miles per hour
timer = 0;//reset timer
reedCounter = maxReedCounter;//reset reedCounter
}
else{
if (reedCounter > 0){//don't let reedCounter go negative
reedCounter -= 1;//decrement reedCounter
}
}
}
if (timer > 2000){
mph = 0;//if no new pulses from reed switch- tire is still, set mph to 0
}
else{
timer += 1;//increment timer
}
}
void displayMPH(){
lcd.setCursor(0,1);
lcd.print("Speed: ");
lcd.setCursor(7,1);
lcd.print(mph);
lcd.setCursor(11,1);
lcd.print(" MPH");
//lcd.print(mph);
//lcd.print(" MPH ");
}
void loop(){
//print mph once a second
displayMPH();
delay(1000);
}