Parking Sensor: Display
Part of the Projects section of Coddy's Arduino journey. Lesson 12 of 24.
The last step puts the exact distance on the screen. The 16x2 LCD is wired the usual way: RS on 12, E on 11, D4 to D7 on 5, 4, 3 and 2.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);The top row never changes, so write Distance: once in setup(), after lcd.begin(16, 2). Only the bottom row is updated in loop().
An LCD keeps every character until something replaces it. Going from 250 cm to 8 cm, printing 8 cm over 250 cm leaves the old end of the line behind, and the screen reads 8 cmcm. Print a few spaces after the text to cover anything a longer number left:
lcd.setCursor(0, 1);
lcd.print(cm);
lcd.print(" cm ");Spaces also avoid the flicker of lcd.clear(), which would blank the whole screen ten times a second.
Challenge
EasyShow the distance on the LCD:
- include
LiquidCrystal.hand createlcd(12, 11, 5, 4, 3, 2) - in
setup():lcd.begin(16, 2)andDistance:on the top row - in
loop(): the distance andcmon the bottom row, like57 cm, with spaces after it
Keep the lights, the beeps and the printing. Press Run, then Check.
Try it yourself
// The distance sensor
const int trigPin = 9;
const int echoPin = 10;
// The warning lights
const int greenPin = 6;
const int yellowPin = 7;
const int redPin = 13;
// The buzzer
const int buzzerPin = 8;
unsigned long lastBeep = 0; // when the last beep started
// Send a ping and return the distance in cm.
long readDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
return duration / 58;
}
// Green when clear, yellow when close, red when too close.
void showLights(long cm) {
digitalWrite(greenPin, LOW);
digitalWrite(yellowPin, LOW);
digitalWrite(redPin, LOW);
if (cm >= 100) {
digitalWrite(greenPin, HIGH);
} else if (cm >= 30) {
digitalWrite(yellowPin, HIGH);
} else {
digitalWrite(redPin, HIGH);
}
}
// Beep faster as the object gets closer.
void beep(long cm) {
if (cm >= 100) {
noTone(buzzerPin);
} else if (cm < 10) {
tone(buzzerPin, 1000); // too close: a steady tone
} else if (millis() - lastBeep >= cm * 10) {
lastBeep = millis();
tone(buzzerPin, 1000, 50);
}
}
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(greenPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(redPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
long cm = readDistance();
Serial.println(cm);
showLights(cm);
beep(cm);
delay(100);
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Projects
3Parking Sensor
Parking Sensor: DistanceParking Sensor: LightsParking Sensor: BeepsParking Sensor: DisplayPractice on your own: Arduino playground