Scalextric Lap Timer using ultrasonic sensor
Dependencies: HCSR04 mbed TextLCD
main.cpp
- Committer:
- MrBedfordVan
- Date:
- 2016-09-28
- Revision:
- 1:034f79c00c98
- Parent:
- 0:b88af2ed370b
- Child:
- 2:b47f8dbf374c
File content as of revision 1:034f79c00c98:
// Scalextric Timer for Ada Lovelace Day // // Uses Nucleo board F072 with LCD Keypad shield // Connect D3 to Trig & D2 to Echo // Connect VCC to 5V (pin CN7 18) // Connect GND to 0V (pin CN7 19) #include "mbed.h" #include "hcsr04.h" // Ultrasonic sensor #include "TextLCD.h" // LCD1602 // serial PC for debug Serial pc(SERIAL_TX, SERIAL_RX); // Ultrasonic sensor HCSR04 usensor(D3,D2); // Trig, Echo // LCD Shield TextLCD lcd(D8, D9, D4, D5, D6, D7); // used to drive display AnalogIn keys(A0); // used to sample buttons Timer lap_timer; Timer wait_timer; // display text on LCD void textLCD(char *text, int line) { char tmpBuf[16]; for (int i = 0; i < 16; i++) tmpBuf[i] = 0x20; for (int i = 0; i < strlen(text); i++) { if (i < 16) tmpBuf[i] = text[i]; lcd.locate(i, line); lcd.putc(tmpBuf[i]); } } int main() { // Variables used int dist = 0; float current_time = 0; int lap_count = 0; float wait_time = 2.0; pc.baud(9600); char lap_string[16]; char laptime_string[16]; // Values to tune float min_laptime = 1.0; // Minimum laptime - time to wait after seeing car before measuring again in seconds int sample_time = 100; // Sample time - time between sampling value from sensor in milliseconds int trigger_distance = 4; // Trigger distance - distance below which the car registers as detected // Intro Screen pc.printf("ARM Sheffield Scalextric Challenge \n"); textLCD("ARM Scalextric ", 0); // Main loop while(1) { usensor.start(); wait_ms(sample_time); dist=usensor.get_dist_cm(); pc.printf("Distance %d\n\r", dist); // Debug to Serial port/USB if (lap_count > 0) { wait_time = wait_timer.read(); } if ((dist < trigger_distance) and (wait_time > min_laptime)) { // spotted car at least a minimum laptime later wait_timer.reset(); wait_timer.start(); if (lap_count == 0) { // First Lap - start timer lap_timer.reset(); lap_timer.start(); pc.printf("Timing... \r"); // Debug textLCD("Timing..........", 1); // lap_count++; } else { // Completed a lap current_time = lap_timer.read(); lap_timer.reset(); pc.printf("Lap : %d, Lap time : %f s \r", lap_count, current_time); sprintf(lap_string, "Lap : %d ", (char*)lap_count); sprintf(laptime_string, "Lap time : %f s, ", current_time); textLCD(" ", 0); textLCD(lap_string, 0); textLCD(" ", 1); textLCD(laptime_string, 1); lap_count++; } } } }