//Setup I2C
#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 16
#define LCD_LINES 2
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
//Define Pins
const int HALL_TRIG = 2; //IRL This is a Digital Hall Efect Sensor with 4 magnets at 90deg.
const int BACKLIGHT_PIN = 3;
const int RESET = 4;
//Define Vars
const float CIRC = 0.00027;
long HALL_TICK = 0;
long ROTATIONS = 0;
bool ROTATION_FLAG = false;
bool RESET_FLAG = false;
bool BACKLIGHT = false;
//
void setup() {
//Setup Interupts
pinMode(HALL_TRIG, INPUT);
pinMode(RESET, INPUT);
pinMode(BACKLIGHT_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(HALL_TRIG), ROTATION_DETECTED, RISING);
attachInterrupt(digitalPinToInterrupt(BACKLIGHT_PIN), CHANGE_BACKLIGHT, RISING);
//Setup LCD
lcd.init();
lcd.setCursor(0, 0);
lcd.print("Miles:");
lcd.setCursor(7, 0);
lcd.print("0.00");
lcd.setCursor(0, 1);
lcd.print("Spins:");
lcd.setCursor(7, 1);
lcd.print("0");
//
}
void loop() {
if(BACKLIGHT == HIGH)
{
lcd.backlight();
}else{
lcd.noBacklight();
}
if(ROTATION_FLAG == true)
{
lcd.setCursor(0, 0);
lcd.print("Miles:");
lcd.setCursor(7, 0);
lcd.print(String((ROTATIONS * CIRC), 2));
lcd.setCursor(0, 1);
lcd.print("Spins:");
lcd.setCursor(7, 1);
lcd.print(ROTATIONS);
ROTATION_FLAG = false;
}
if(digitalRead(RESET) == HIGH)
{
lcd.backlight();
delay(20);
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("HOLD TO RESET!");
for(int i = 9; i != 0; i--)
{
if(digitalRead(RESET) == LOW)
{
lcd.clear();
ROTATION_FLAG = true;
return;
}
lcd.setCursor(7, 1);
lcd.print(i);
lcd.print(i);
delay(1000);
}
lcd.clear();
lcd.setCursor(3, 0);
lcd.print("RESETTING!");
lcd.setCursor(0, 1);
for(int i = 0; i < 17; i++)
{
lcd.print("*");
delay(200);
}
lcd.clear();
HALL_TICK = 0;
ROTATIONS = 0;
ROTATION_FLAG = true;
RESET_FLAG = false;
return;
}
}
void ROTATION_DETECTED(){
if(HALL_TICK < 3)
{
HALL_TICK++;
}else{
HALL_TICK = 0;
ROTATIONS++;
ROTATION_FLAG = true;
}
}
void CHANGE_BACKLIGHT(){
static unsigned long last_interrupt_time = 0;
unsigned long interrupt_time = millis();
if (interrupt_time - last_interrupt_time > 200)
{
BACKLIGHT = !BACKLIGHT;
}
last_interrupt_time = interrupt_time;
}