HC SR04 Ultrasonic sensor with ESP 8266 | NodeMCU
Ultra Sonic Sensor (HC-SR04) for distance measurement with NodeMCU
Ever noticed your car informing about possible collision!!! How does a distance between two objects measured without a physical tape. It possible that collision detection and distance measuring sensors are behind it. Today we will talk about ultrasonic sensor that works on principal of SONAR.
There are a lot of ways to detect an object and measure distance. HC SR04 is a low cost ultra sonic sensor that can also be used to detect any object in path for your robotic car and measure distance of the object. It has a a transmitter and a receiver that looks like an eye. Sensor works on 5V. It has a range of 2 cm to 400 cm with a precision of 3 mm. When trigger pin is activated, sensor sends a signal from transmitter at 40 kHz and listens for an echo. Up on receiving signal, echo pin goes high. Sound velocity is know in the medium and this is used to measure distance. Trigger input signal is for 10 micro seconds.
Distance = duration of echo pin (HIGH) * Sound velocity in the medium / 2
(Sound wave has to cover twice the distance from module to object)
Now lets connect to a NodeMCU and measure distance. If you want to use this readings in your projects, Would recommend to take 4 or 5 readings and take a meadian/mean.
Parts needed
1. Ultrasonic Sensor HC-SR04
2. NodeMCU
3. Jumper wires
const int trigger = D3; const int echo = D4; #define SOUND_VELOCITY 0.034 long duration; float distance; void setup() { Serial.begin(115200); pinMode(trigger, OUTPUT); pinMode(echo, INPUT); } void loop() { digitalWrite(trigger, LOW); delayMicroseconds(2); digitalWrite(trigger, HIGH); delayMicroseconds(10); digitalWrite(trigger, LOW); duration = pulseIn(echo, HIGH); distance = duration * SOUND_VELOCITY/2; Serial.print("Distance (in cms): "); Serial.println(distance); delay(2000); }
We will use D3 as trigger and D4 as echo. Serial monitor will be used to see the distance measured.
Connections
1. NodeMCU Vin -> HC SR04 Vcc
2. NodeMCU Gnd -> HC SR04 Gnd
3. NodeMCU D3 -> HC SR04 Trig
4. NodeMCU D4 -> HC SR04 Echo
Once measuring starts, move the sensor head to face different objects and measure distance.
Trouble shooting
1. Always upload the code to NodeMCU and then connect sensor. If you connect before, aurdino might not upload your code to NodeMCU.
Comments
Post a Comment