Skip to content

Instantly share code, notes, and snippets.

@jes
Created December 12, 2017 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jes/6f7550545a094f1517f9b96ee6889027 to your computer and use it in GitHub Desktop.
Save jes/6f7550545a094f1517f9b96ee6889027 to your computer and use it in GitHub Desktop.
/*
Speedo converter by jes
How to re-program the board:
Orient the board so the programming header is at top left and the LED is at bottom left.
Pins are as follows, from top:
1. Reset
2. 0 (RX)
3. 1 (TX)
4. +5V
5. GND
Remove the ATmega from an Arduino UNO board.
Connect the pins as detailed above.
Plug the UNO into the USB port
Select "ATmega328 on a breadboard (8MHz internal clock)" as the board type
Upload program
*/
#include <TimerOne.h>
float wheel_circumference = 1.759; // metres
int ledpin = 8;
int pin = 9;
int hall_pin = A0;
unsigned long last_pass;
unsigned long ms_elapsed;
unsigned long min_ms_elapsed = 45;
int hall_state = 0;
void setup() {
pinMode(pin, OUTPUT);
pinMode(ledpin, OUTPUT);
digitalWrite(ledpin, HIGH);
delay(250);
digitalWrite(ledpin, LOW);
delay(250);
digitalWrite(ledpin, HIGH);
delay(250);
digitalWrite(ledpin, LOW);
Timer1.initialize(100);
Timer1.pwm(pin, 512, 100);
}
void set_delay_for_speed(float mph) {
if (mph < 1)
mph = 1;
Timer1.setPeriod(54000 / mph);
}
int my_digitalRead(int pin) {
int val = analogRead(pin);
return val > 530;
}
// the loop function runs over and over again forever
void loop() {
int readstate = my_digitalRead(hall_pin);
digitalWrite(ledpin, readstate);
if (readstate != hall_state && (millis() - last_pass) > min_ms_elapsed) {
hall_state = readstate;
if (readstate == 1) {
ms_elapsed = millis() - last_pass;
last_pass = millis();
}
}
// if it takes too long to pass, increase ms_elapsed as we are obviously slowing down
if ((millis() - last_pass) > ms_elapsed) {
ms_elapsed = millis() - last_pass;
}
if (ms_elapsed == 0)
ms_elapsed = 1;
float wheel_speed = wheel_circumference / ms_elapsed; // metres per millisecond
float mph = wheel_speed * 2236.936; // metres per millisecond to miles per hour
set_delay_for_speed(mph);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment