top of page

This is an Arduino program that uses the LiquidCrystal library to display the distance measured by an ultrasonic sensor on an LCD screen. The program uses the trigPin and echoPin to trigger the sensor and measure the duration of the echo, respectively. This duration is then used to calculate the distance in centimeters and inches and display it on the LCD screen. The program uses the lcd.begin() method to initialize the interface to the LCD screen and the lcd.setCursor() and lcd.print() methods to display the distance on the screen. The program runs in an infinite loop, constantly measuring and updating the distance on the screen.

#include <LiquidCrystal.h> // include LiquidCrystal

LiquidCrystal lcd(1, 2, 3, 4, 5, 6); // create LCD object

const int trigPin = 8; // trigger pin

const int echoPin = 9; // echo pin

long duration; // duration of echo

int distanceCm, distanceInch; // distances in cm and inches

void setup() {

lcd.begin(16,2); // initialize LCD

pinMode(trigPin, OUTPUT); // set trigger pin as output

pinMode(echoPin, INPUT); // set echo pin as input

}

void loop() {

digitalWrite(trigPin, LOW); // set trigger pin low

delayMicroseconds(2); // delay 2 microseconds

digitalWrite(trigPin, HIGH); // set trigger pin high

delayMicroseconds(10); // delay 10 microseconds

digitalWrite(trigPin, LOW); // set trigger pin low

duration = pulseIn(echoPin, HIGH); // measure echo duration

distanceCm= duration*0.034/2; // calculate distance in cm

distanceInch = duration * 0.01330 / 2; // calculate distance in inches

lcd.setCursor(0,0); // set cursor position on LCD

lcd.print("Distance: "); // print "Distance" on LCD

lcd.print(distanceCm); // print distance in cm on LCD

lcd.print(" cm"); // print units on LCD

delay(10); // delay 10 milliseconds

lcd.setCursor(0,1); // set cursor position on LCD

lcd.print("Distance: "); // print "Distance" on LCD

lcd.print(distanceInch); // print distance in inches on LCD

lcd.print(" inch"); // print units on LCD

delay(10); // delay 10 milliseconds

}

Digital material culture

bottom of page