This is a simple example of using the ultrasonic sensor (HC-SR04) in Arduino where we will turn on a led with the variation of distance and print the distance from an object to the serial monitor.
- Input: 1 pin for ultrasonic sensor (Echo pin)
- Output: 4 pins for LEDs
1 pin for Trig
- Conditions of the distance
- Less than 5: turn on all LEDs
- Form 5 to 10: turn on three LEDs
- Form 10 to 15: turn on two LEDs
- Form 15 to 20: turn on one LED
- Over 20: turn off all LEDs
- Components Requirements
- Arduino Uno x 1
- Ultrasonic Sensor (HC-SR04). x 1
- Mini-BreadBoard x 1
- 1 k-ohm Resistor x 3
- Jumpers.
- LED x 4
- Mini-BreadBoard x 1
- 1 k-ohm Resistor x 3
- Jumpers.
- LED x 4
- Making
the ultrasonic sensor is an electronic device that measures the distance of a target object by emitting ultrasonic sound waves, and converts the reflected sound into an electrical signal.
- Coding
int pinTrig = 2;
int pinEcho = 4;
int led1 = 9;
int led2 = 10;
int led3 = 11;
int led4 = 12;
float distance;
void setup() {
Serial.begin(9600);
//passes the value 9600 to the speed parameter.
//This tells the Arduino to get ready to exchange messages with the Serial Monitor at a data rate of 9600 bits per second.
//That's 9600 binary ones or zeros per second, and is commonly called a baud rate.
pinMode(pinTrig, OUTPUT);
pinMode(pinEcho, INPUT);
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
pinMode(led3,OUTPUT);
pinMode(led4,OUTPUT);
}
void loop() {
distance = checkDistance();
if(distance<5){
digitalWrite(led1,1);
digitalWrite(led2,1);
digitalWrite(led3,1);
digitalWrite(led4,1);
}else if(distance<10){
digitalWrite(led1,1);
digitalWrite(led2,1);
digitalWrite(led3,1);
digitalWrite(led4,0);
}else if(distance<15){
digitalWrite(led1,1);
digitalWrite(led2,1);
digitalWrite(led3,0);
digitalWrite(led4,0);
}else if(distance<20){
digitalWrite(led1,1);
digitalWrite(led2,0);
digitalWrite(led3,0);
digitalWrite(led4,0);
}else{
digitalWrite(led1,0);
digitalWrite(led2,0);
digitalWrite(led3,0);
digitalWrite(led4,0);
}
Serial.println(checkDistance());
delay(50);
}
float checkDistance(){
float cm;
digitalWrite(pinTrig, 0);
delayMicroseconds(2);
digitalWrite(pinTrig, 1);
delayMicroseconds(10);
digitalWrite(pinTrig, 0);
cm = pulseIn(pinEcho, 1)/58.0;
cm = (int(cm * 100.0))/100.0;
return cm;
}
//prepared by Rothny
//Lead. by Dr. Kwanghoon Kim
No comments:
Post a Comment