Example Code for Raspberry Pi-Get Distance

Last revision 2026/01/21

This project demonstrates how to use the A02YYUW Ultrasonic Sensor with Raspberry Pi to get distance measurements via UART.

Hardware Preparation

  • Raspberry Pi 4B
  • Raspberry Pi IO Expansion Board
  • A02YYUW Ultrasonic Sensor (Purchase Link)
  • 4P Connector

Software Preparation

Wiring Diagram

SEN0311  Raspberry Pi Connection

Other Preparation Work

Download and install the DFRobot_RaspberryPi_A02YYUW library from GitHub.

Sample Code

# -*- coding:utf-8 -*-

'''
  # demo_get_distance.py
  #
  # Connect board with raspberryPi.
  # Run this demo.
  #
  # Connect A02 to UART
  # get the distance value
  #
  # Copyright   [DFRobot](https://www.dfrobot.com), 2016
  # Copyright   GNU Lesser General Public License
  #
  # version  V1.0
  # date  2019-8-31
'''

import time

from DFRobot_RaspberryPi_A02YYUW import DFRobot_A02_Distance as Board

board = Board()

def print_distance(dis):
  if board.last_operate_status == board.STA_OK:
    print("Distance %d mm" %dis)
  elif board.last_operate_status == board.STA_ERR_CHECKSUM:
    print("ERROR")
  elif board.last_operate_status == board.STA_ERR_SERIAL:
    print("Serial open failed!")
  elif board.last_operate_status == board.STA_ERR_CHECK_OUT_LIMIT:
    print("Above the upper limit: %d" %dis)
  elif board.last_operate_status == board.STA_ERR_CHECK_LOW_LIMIT:
    print("Below the lower limit: %d" %dis)
  elif board.last_operate_status == board.STA_ERR_DATA:
    print("No data!")

if __name__ == "__main__":
  dis_min = 0   #Minimum ranging threshold: 0mm
  dis_max = 4500 #Highest ranging threshold: 4500mm
  board.set_dis_range(dis_min, dis_max)
  while True:
    distance = board.getDistance()
    print_distance(distance)
    time.sleep(0.3) #Delay time < 0.6s

Result

The terminal will display the distance measurement in millimeters (e.g., Distance 1953 mm) or error messages if there's an issue.

Ensure the Raspberry Pi's UART is enabled before running the code.

Was this article helpful?

TOP