Smart Device with Arduino
This is a simple project of using the ultrasonic sensor (HC-SR04) in Arduino that will turn on a led and buzzer with the variation of distance and print the distance from an object to the serial monitor.
Components
- Connect VCC on the ultrasonic sensor to the 5V pin on the Arduino.
- Connect the Trig pin on the ultrasonic sensor to pin 2 on the Arduino.
- Connect the Echo pin on the ultrasonic sensor to pin 3 on the Arduino.
- Connect the GND on the ultrasonic sensor to GND on the Arduino.
After that, make the connections for the buzzer and the Arduino. Connect the positive pin on the buzzer with pin 10 on the Arduino and the buzzer's negative pin with the GND pin on the Arduino
or connect a LED to the board
Write the code and upload it to the Arduino board
-------------------------------------------------------------------------------------------------------------------------
//code
const int trigPin = 9;
const int echoPin = 10;
const int buzzer = 11;
const int ledPin = 13;
long duration;
int distance;
int safetyDistance;
void setup(){
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzer,OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration*0.034/2;
safetyDistance = distance;
//you can change the distance in here
if(safetyDistance <=20){
digitalWrite(buzzer, HIGH);
digitalWrite(ledPin, HIGH);
}
else{
digitalWrite(buzzer, LOW);
digitalWrite(ledPin, LOW);
Serial.print("Distance : ");
Serial.print(distance);
}
}
--------------------------------------------------------------------------------------------------------------------------
for full video - https://youtu.be/sDo-uHNM1Xg