It displays the large number, but then just goes crazy and displays random characters. Here is my code below:
#include <LiquidCrystal.h>
// Define LCD pin connections
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
// Define ultrasonic sensor pins
const int trigPin = 6;
const int echoPin = 10;
const int contrastPin = 9;
void setup() {
// Initialize serial communication for debugging
Serial.begin(9600);
pinMode(contrastPin, OUTPUT);
analogWrite(contrastPin, 100);
// Set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Set up ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Measure distance using ultrasonic sensor
long duration, distance_cm;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance_cm = duration * 0.034 / 2; // Convert to centimeters
// Print distance to Serial monitor for debugging
Serial.print("Distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
// Display distance on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance:");
lcd.setCursor(0, 1);
lcd.print(distance_cm);
lcd.print(" cm");
// Wait before taking next measurement
delay(600);
}
Please help. I have increased the delay to no avail.