MagicCode Lesson 13
Find distance to objects with the ultrasonic sensor
Ultrasonic sensor is used to measure the distance to objects in front of the sensor by using ultrasonic waves.The human body doesn’t sensitive for this signal. Therefor we can’t hear any sound when it is working.
- Using HC-SR04 ultarsonic sensor and getting outputs of distances
- Apply Ultrasonic sensor in projects
Any kind of ultrasonic sensor works on same way. For measuring distance to object it uses ultrasonic waveform. The sensor have two parts. One is wave transmitter part and other one is receiving part. The transmitter part emits an ultrasonic wave and receives the reflected waveform back from the emitter. The time duration between transmit and receive is used to measure the distance. If the time duration is low then object is near. If the time duration is high the object is too far. Distance and the time duration is directly proportional parameters. Distance between object and the sensor can be determined by following equation.
Distance=(speed of ultrasound wave in air )*(time duration)/2
Speed of ultrasound wave in air is 340 meters per second. To measure the distance, we have to trigger the transmitter in certain time duration. If this time duration is very small, then it cant be measured. If this is too high it can cause to noises. Therefor it emits ultrasonic waves in small certain time durations. Then checks the receiver part(echo pin) until it detects.
Connect the ultrasonic sensor module to magicbit using connector wire. In here we connect sensor module to the upper left (D32) connector on the Magicbit. We are using HC-SR04 ultrasonic sensor for this example.
Drag and drop following blocks to create the following script. then you can read the measured distance by the sensor on Magicbit OLED display.
This program also starts by clicking the green flag. After that OLED display is cleared. Then continuously you can observe the distance through the OLED display.