Stap 3: De Arduino schets
Hier is de schets die ik gebruiken voor het uitvoeren van de chronometer.
// Load libraries for LCD display and create and lcd object#include <Wire.h>#include <LiquidCrystal_I2C.h>LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);// Initialise variablesint sensorPin = A0;int ledPin = 12;int sensorValue = 0;int beepPin = 3;unsigned int start = 0;unsigned int lap = 0;unsigned int tempo = 0;unsigned int bestLap = 1000000; // High value so that the first lap is always a best lapchar last[16];char best[16]; void setup(){// Initialise the LCD display lcd.begin(16,2); lcd.backlight(); lcd.setCursor(0, 0); lcd.print("Ready"); // Initialise serial communication at 9600 bps Serial.begin(9600); // Power up the IR sensor pinMode(ledPin, OUTPUT); digitalWrite(ledPin, HIGH);}void loop(){ sensorValue = analogRead(sensorPin); if (sensorValue > 130) // An object is detected { tempo = millis(); // Record the current time tone(3, 440, 50); // Play a beep lap = tempo - start; // Calculate the lap time start = tempo; // Reset the clock // Check if this is the best lap if (lap < bestLap) { bestLap = lap; }// Calculate the seconds and milliseconds for nicer printout of lap time unsigned int sec = lap / 1000; unsigned int msec = lap - sec*1000; // Print out the lap time on the serial port sprintf(last, "Last: %02u\"%03u", sec, msec); Serial.println(last);// Print out the lap time on the LCD display lcd.setCursor(0, 0); // Set the cursor on the first diplay line lcd.print(last);// Calculate the seconds and milliseconds for nicer printout of best lap time unsigned int bestSec = bestLap / 1000; unsigned int bestMsec = bestLap - bestSec*1000;// Print out the best lap time on the serial port sprintf(best, "Best: %02u\"%03u", bestSec, bestMsec); Serial.println(best);// Print out the best lap time on the LCD display lcd.setCursor(0, 1); // Set the cursor on the second display line lcd.print(best); Serial.println("---"); delay(500); // Needed to avoid that the car triggers multiple detections }}