Raspberry Pi Raspberry+ Ultrasonic Module Ranging

Raspberry Pi Raspberry+ Ultrasonic Module Ranging

Talk is cheak,show me the code!

import RPi.GPIO as GPIO
import time

makerobo_TRIG = 11 # Tring control pin of ultrasonic module
makerobo_ECHO = 12 # Ultrasonic module Echo control pin

# Ultrasonic module initialization work
def makerobo_setup():
  GPIO.setmode(GPIO.BOARD) # Use actual physical pins for GPIO port
  GPIO.setwarnings(False) # Ignore GPIO operation attention warning
  GPIO.setup(makerobo_TRIG, GPIO.OUT) # Tring is set to output mode
  GPIO.setup(makerobo_ECHO, GPIO.IN) # Echo is set to input mode

# Ultrasonic calculation distance function
def ur_disMeasure():

  GPIO.output(makerobo_TRIG, 0) # start to start
  time.sleep(0.000002) # Delay 2us

  GPIO.output(makerobo_TRIG, 1) # Ultrasonic start signal, delay 10us
  time.sleep(0.00001) # send out ultrasonic pulse
  GPIO.output(makerobo_TRIG, 0) # set to low level

  
  while GPIO.input(makerobo_ECHO) == 0: # Waiting for the return signal
    us_a = 0
  us_time1 = time.time() # Get current time
  while GPIO.input(makerobo_ECHO) == 1: # Return signal cut-off information
    us_a = 1
  us_time2 = time.time() # Get current time

  us_during = us_time2-us_time1 # Convert microsecond time

  # The propagation speed of sound velocity in the air is 340m/s. Ultrasonic waves have to experience a transmission signal and an echo information.
  # The calculation formula is as follows:
  return us_during * 340/2 * 100 # Find the distance

# Loop function
def makerobo_loop():
  while True:
    us_dis = ur_disMeasure() # Get ultrasonic calculation distance
    print (us_dis,'cm') # Print the ultrasonic distance value
    print ('')
    time.sleep(0.3) # Delay 300ms 

# Resource release function
def destroy():
  GPIO.cleanup() # Release resources

# Program entry
if __name__ == "__main__":
  makerobo_setup() # Call the initialization function
  try:
    makerobo_loop() # call loop function
  except KeyboardInterrupt: # When Ctrl+C is pressed, the destroy() subroutine will be executed.
    destroy() # release resources

The connection is as shown in the figure below, to be tested:

Reference: https://cloud.tencent.com/developer/article/1746129 Raspberry Pi Raspberry + Ultrasonic Module Ranging-Cloud + Community-Tencent Cloud