In this Video Lesson I will teach you how to use echolocation to measure distances. We will use the HC-SR04 Ultrasonic Sensor, and will use the Raspberry Pi Pico W. We will explain how echolocation works, and show you how the sensor works. We will do the math, and then create the code for making measurements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# ==================================================================== # DISCLAIMER: # This code is provided as-is for educational and experimental # purposes only. The author makes no representations or warranties of # any kind concerning the safety, suitability, or accuracy of this # code. Use at your own risk. The author assumes no liability for any # damages, system failures, security breaches, or network issues # resulting from the use or implementation of this script. # ==================================================================== import machine import time TRIG_PIN = 16 ECHO_PIN = 17 TRIG = machine.Pin(TRIG_PIN,machine.Pin.OUT) ECHO = machine.Pin(ECHO_PIN,machine.Pin.IN) def distance(): TRIG.low() time.sleep_us(2) TRIG.high() time.sleep_us(10) TRIG.low() while (ECHO.value()==0): pass time1=time.ticks_us() while (ECHO.value()==1): pass time2=time.ticks_us() pingTime=time.ticks_diff(time2,time1)/2 d=.0343*pingTime return d while True: dist=distance() print("Distance to Target: ",dist," cm") time.sleep_ms(250) |


