PCBX
Published

SR04 Ultrasonic Distance Alarm

SR04 Ultrasonic Distance Alarm: a precise monitoring solution that alerts you to distance changes, enhancing safety and efficiency,

BeginnerFull instructions provided177

Things used in this project

Story

Read more

Schematics

20241204161745_PVIv2pjzUR.png

Code

SR04 Ultrasonic Distance Alarm

Arduino
#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);
}

Credits

PCBX
33 projects • 11 followers
Customer Success: Your one-stop solution for PCB and PCBA services, plus component sourcing. Enjoy FREE online simulation and EDA.
Contact

Comments

Please log in or sign up to comment.