SR04_URM10: Ultrasonic Sensor
This Python code demonstrates how to read ultrasonic waves using an SR04 or URM10 ultrasonic sensor. The Arduino main control board is connected to a Windows or Linux computer, the Trig pin of the sensor is connected to D7, and the Echo pin is connected to D8 of the main control board.
# -*- coding: UTF-8 -*-
# Experiment effect: Read ultrasonic waves
# Connection: Connect an Arduino main control board to a Windows or Linux computer, use SR04 or URM10 ultrasonic sensor, connect Trig to D7, and Echo to D8
import time
from pinpong.board import Board,Pin,SR04_URM10 # Import SR04_URM10
Board("uno").begin() # Initialization, select the board type (uno, leonardo, xugu) and port number. If no port number is entered, automatic recognition will be performed
#Board("uno","COM36").begin() # Initialization by specifying the port under Windows
#Board("uno","/dev/ttyACM0").begin() # Initialization by specifying the port under Linux
#Board("uno","/dev/cu.usbmodem14101").begin() # Initialization by specifying the port under Mac
TRIGER_PIN = Pin(Pin.D7)
ECHO_PIN = Pin(Pin.D8)
sonar = SR04_URM10(TRIGER_PIN,ECHO_PIN)
while True:
dis = sonar.distance_cm() # Get the distance, unit in centimeters (cm)
print("distance = %d cm"%dis)
time.sleep(0.1)