HC-SR04 distance sensor Python code on Orange Pi

Connect the HC-SR04 to Orange Pi

The HC-SR04 is a cheap and easy to use sensor, used to measure distance with ultrasound. It can be used in many projects where you trigger an action based on an object or person entering an area, like an “alarm”, as I showed in my previous post. Also, you often see this sensor as part of more interesting projects such as robots, like this one.


To make the sensor work with the Orange Pi, this is the connection I used previously:

distance sensor orange pi diagram

And a picture of how it looks like:

hc-sr04 distance sensor connected to orange pi

For full details please check my original post.

Based on this setup and on duxingkei33 code, I wrote a Python code to read this distance sensor. I think having Python code for this sensor will make it easier to integrate the sensor in other projects written in Python.

How to control HC-SR04 in Python

First clone the library:

git clone https://github.com/duxingkei33/orangepi_PC_gpio_pyH3
cd orangepi_PC_gpio_pyH3
sudo python setup.py install

Then create a new Python script, let’s call it distance.py, and type in the code below.

from pyA20.gpio import gpio
from pyA20.gpio import port
from time import sleep
import time

#initialize the gpio module
gpio.init()

#setup the ports
gpio.setcfg(port.PC4, gpio.OUTPUT)
gpio.setcfg(port.PC7, gpio.INPUT)

#set trig to low
gpio.output(port.PC4, gpio.LOW)
sleep(0.5)

while True:
    #send pulse
    gpio.output(port.PC4, gpio.HIGH)
    sleep(0.3)
    gpio.output(port.PC4, gpio.LOW)

    #wait for echo to start
    while (gpio.input(port.PC7) == 0):
        pass
    start = time.time()

    #wait for echo to end
    while (gpio.input(port.PC7) == 1):
        pass
    end = time.time()
    
    #get distance in cm
    print((end - start)/58.0*1000000)
    sleep(1)

You can find the code on github here. The names of pins are based on the image below, that I found on this forum:

orange pi pin names

Now run it with Python, as sudo:

sudo python distance.py

Here is a video of the sensor in action:

As you can see, although rarely it can record weird values, it mostly works fine and it reacts quickly.

Make your own Kodi add-on in Python
ZeroCam Raspberry Pi Zero NoIR Camera

Leave a Reply

Your email address will not be published / Required fields are marked *