Created
June 1, 2017 15:47
-
-
Save matt448/9c7fdbed5a885bad57531d2de545fb23 to your computer and use it in GitHub Desktop.
Arduino based speedometer using a Nextion HMI Display
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "Nextion.h" | |
const int lightPin = 0; | |
const int hardwareCounterPin = 5; | |
const int samplePeriod = 1000; //in milliseconds | |
const float pulsesPerMile = 4000; | |
const float convertMph = pulsesPerMile/3600; | |
unsigned int count; | |
float mph; | |
unsigned int imph; | |
int roundedMph; | |
int previousMph; | |
/* | |
* Declare a text object [page id:0,component id:1, component name: "t0"]. | |
*/ | |
NexNumber n0 = NexNumber(1, 1, "n0"); | |
void fadeIn(int delayval) { | |
for (int i=0; i <= 100; i++){ | |
sendCommand("dim=dim+1"); | |
delay(delayval); | |
} | |
} | |
void fadeOut(int delayval) { | |
for (int i=100; i >= 0; i--){ | |
sendCommand("dim=dim-1"); | |
delay(delayval); | |
} | |
} | |
void setup(void) { | |
pinMode(hardwareCounterPin, INPUT_PULLUP); | |
TCCR1A=0; //Configure hardware counter | |
TCNT1 = 0; // Reset hardware counter to zero | |
nexInit(); | |
sendCommand("spax=5"); //set text spacing value | |
sendCommand("dims=0"); //set default dim level to zero | |
fadeIn(20); | |
delay(2000); | |
fadeOut(10); | |
sendCommand("page 1"); | |
fadeIn(15); | |
} | |
/* | |
****************** | |
MAIN LOOP | |
****************** | |
*/ | |
void loop() { | |
int reading = analogRead(lightPin); | |
int brightness = (reading / 2) / 15; | |
if(brightness > 15){ | |
brightness = 15; | |
} | |
bitSet(TCCR1B, CS12); // start counting pulses | |
bitSet(TCCR1B, CS11); // Clock on rising edge | |
delay(samplePeriod); // Allow pulse counter to collect for samplePeriod | |
TCCR1B = 0; // stop counting | |
count = TCNT1; // Store the hardware counter in a variable | |
TCNT1 = 0; // Reset hardware counter to zero | |
mph = (count/convertMph)*10; | |
//Serial.print("float mph 10x: "); | |
//Serial.println(mph); | |
imph = (unsigned int) mph; | |
//Serial.print("int mph 10x: "); | |
//Serial.println(imph); | |
int x = imph / 10; | |
int y = imph % 10; | |
//Serial.print("Pre-rounding mph: "); | |
//Serial.print(x); | |
//Serial.print("."); | |
//Serial.println(y); | |
if(y >= 5){ | |
roundedMph = x + 1; | |
}else{ | |
roundedMph = x; | |
} | |
// Don't display mph readings that are more than 50 mph higher than the | |
// previous reading because it is probably a spurious reading. | |
if((roundedMph - previousMph) > 50){ | |
n0.setValue(previousMph); | |
}else{ | |
n0.setValue(roundedMph); | |
} | |
previousMph = roundedMph; // Set previousMph for use in next loop. | |
} |
Author
matt448
commented
Jun 1, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment