/*
Speedo Code
*/

#include < LiquidCrystal.h>

LiquidCrystal lcd(5, 4, 3, 2, 1, 0);
int sensorPin = 7; // select the input pin for the hall effect sensor
int ledPin = 8; // select the pin for the LED
int buttonPin = 6;
int sensorValue = 510; // variable to store the value coming from the sensor. Default value (no magnet) drifts between 507 and 511
int sensorState = 0;
int lastsensorState = 0;
int sensorCount = 0;
int wheelDia = 75;
unsigned long rpm = 0;
unsigned long mph = 0;
unsigned long startTime = 0;
unsigned long stopTime = 0;
unsigned long sampleLength = 1000;

void setup() {
// declare the ledPin as an OUTPUT:
pinMode(ledPin, OUTPUT);
pinMode(sensorPin, INPUT);
pinMode(buttonPin, INPUT);
lcd.begin(16, 2);
lcd.setCursor(0,0);
lcd.print("Your Speed is:");
}

void loop() {
// if(digitalRead(buttonPin)==LOW){
// lcd.setCursor(0,0);
// lcd.print("Calibration Cycle");
// delay(3000);
// lcd.setCursor(0,0);
// lcd.print("Input Wheel Diameter");
// sensorCount = 0;
// while(digitalRead(buttonPin)==HIGH){
// digitalWrite(ledPin, HIGH);
// sensorValue = analogRead(sensorPin);
// if (sensorValue > 650){
// sensorState = 1;
// if (sensorState != lastsensorState){
// sensorCount++;
// lastsensorState = sensorState;
// delay(3);
// }
// }
// else {
// sensorState = 0;
// lastsensorState = 0;
// delay(3);
// }
// wheelDia = (sensorCount);
// lcd.setCursor(9,1);
// lcd.print(" ");
// lcd.setCursor(8,1);
// lcd.print(" ");
// lcd.setCursor(7, 1);
// lcd.print(sensorCount);
// }
// digitalWrite(ledPin, LOW);
// lcd.setCursor(0,0);
// lcd.print("Confirmed");
// delay(3000);
// lcd.setCursor(0,0);
// lcd.print("Your Wheel Diameter");
// lcd.setCursor(9,1);
// lcd.print(wheelDia);
// delay(3000);
// }
if(1==0){}
else{
startTime = millis();
stopTime = startTime + sampleLength;
while(millis() < stopTime){
sensorValue = analogRead(sensorPin);
if (sensorValue > 650){
sensorState = 1;
if (sensorState != lastsensorState){
sensorCount++;
lastsensorState = sensorState;
delay(3);
}
}
else {
sensorState = 0;
lastsensorState = 0;
delay(3);
}
}

rpm = sensorCount*60000/sampleLength;
mph = wheelDia*3.1416*rpm*.00003728227;

lcd.setCursor(9,1);
lcd.print(" ");
lcd.setCursor(8,1);
lcd.print(" ");
lcd.setCursor(7, 1);
lcd.print(mph);

sensorCount = 0;
sensorState = 0;
lastsensorState = 0;
}
}