Scalextric Lap Timer using ultrasonic sensor

Dependencies:   HCSR04 mbed TextLCD

main.cpp

Committer:
MrBedfordVan
Date:
2015-12-01
Revision:
0:b88af2ed370b
Child:
1:034f79c00c98

File content as of revision 0:b88af2ed370b:

#include "mbed.h"
#include "hcsr04.h"

Serial pc(SERIAL_TX, SERIAL_RX);
HCSR04  usensor(D2,D4);
DigitalOut myled1(LED1);
Timer t;
Timer wait_t;

int main()
{
    int dist = 0;
    float current_time = 0;
    float fastest_time = 99999;
    float wait_time = 2.0;
    int lap_count = 0;
    int fastest_lap = 0;
    pc.baud(9600);
    myled1 = 1;
    
    float min_laptime = 1.0; // s
    int num_laps = 10;
    int sample_time = 100; //ms

    pc.printf("ARM Sheffield Scalextric Challenge \n");
 
    while(lap_count < num_laps+1) {
       usensor.start();
       wait_ms(sample_time);
       dist=usensor.get_dist_cm();
       //pc.printf("Distance %d\n\r", dist);
       if (lap_count > 0) { 
         wait_time = wait_t.read();
       }
       if ((dist < 10) and (wait_time > min_laptime)) { // spotted car at least a minimum laptime later
         myled1 = 1;
         wait_t.reset();
         wait_t.start();
         if (lap_count == 0) {
           t.reset();
           t.start();
           pc.printf("Timing... \r");
           lap_count++; 
         } else {      
           //t.stop();
           current_time = t.read();
           t.reset();
           if (current_time < fastest_time) {
             fastest_time = current_time;
             fastest_lap = lap_count;
           }
           pc.printf("Lap : %d, Lap time : %f s , Fastest Lap Time : %f s \r", lap_count, current_time, fastest_time);
           lap_count++; 
        }
       }  else { 
          myled1 = 0;
       } 
    }   
    pc.printf("\n GAME OVER \n");
    pc.printf("Fastest Lap Time : %f s on Lap : %d \n", fastest_time, fastest_lap);

    t.stop();
    wait_t.stop();

}