1. When the circuit is activated, SR04 continuously measures the distance and displays the detected value in real time on LCD1602.
2. When the ultrasonic distance measurement is less than 50cm, the LED flashes; when it is greater than 50cm, the LED does not flash.
3. When the ultrasonic distance measurement exceeds 200cm, the LCD will not display anything.
3D Online Simulation#include <LiquidCrystal.h>
// Initialize LCD1602
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
// Define pins
const int trigPin = 9;
const int echoPin = 10;
const int ledPin = 8;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize LCD1602
lcd.begin(16, 2);
// Set TRIG and ECHO pins as output and input
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// Clear LCD display
lcd.clear();
// Send a 10us pulse to the TRIG pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the pulse time from the ECHO pin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance
float distance = (duration / 2) * 0.0343;
// Display the distance
lcd.print("Dist:");
lcd.print(distance);
lcd.print(" cm");
// Control the LED
if (distance < 50) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
// If the distance is greater than 200cm, do not display
if (distance > 200) {
lcd.clear();
}
// Delay
delay(500);
}
Simulate your project free on PCBX:
https://www.pcbx.com/forum?mtm_campaign=E&mtm_kwd=hack
Register now to get free PCB & PCBA coupons:
Comments
Please log in or sign up to comment.