Menu
CoddyTech

Distance on the LCD

Part of the Displays and Sensors section of Coddy's Arduino journey. Lesson 23 of 24.

A sensor and a screen make an instrument that works without a computer: here the HC-SR04 measures and the LCD shows the distance.

Every step comes from earlier lessons. Measure the echo time, turn it into centimetres, and print it on the bottom row with the unit after it:

int cm = duration * 0.034 / 2;

lcd.setCursor(0, 1);
lcd.print(cm);
lcd.print(" cm    ");

The spaces after cm matter. Going from 150 cm to 20 cm, the new text is shorter, and without them the screen would show 20 cmm. Here the distance is kept in an int: whole centimetres are easier to read on a small screen.

challenge icon

Challenge

Medium

The LCD shows Distance: on the top row and the sketch measures the echo time. Show the distance under it:

  • turn the time into whole centimetres
  • at the start of the bottom row, print the number and then cm, like 25 cm
  • cover leftover characters with spaces

Press Run, move the object, then Check.

Try it yourself

#include <LiquidCrystal.h>

// RS, E, D4, D5, D6, D7
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const int trigPin = 9;
const int echoPin = 10;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  lcd.begin(16, 2);
  lcd.print("Distance:");
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);
  // work out the centimetres and show them on the bottom row, like 25 cm
  delay(200);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Displays and Sensors

Practice on your own: Arduino playground