I have been trying to run the following code on a Raspberry Pi, to use the ultrasonic sensor HC-SR04 with an Arduino that is a slave to a Raspberry Pi:
from nanpy import ArduinoApi
from nanpy import SerialManager
from time import sleep
connection = SerialManager(device='/dev/ttyUSB0')
trigPin = 9
echoPin = 10
a = ArduinoApi(connection=connection)
a.pinMode(trigPin, a.OUTPUT)
a.pinMode(echoPin, a.INPUT)
def loop():
a.digitalWrite(trigPin, a.LOW)
sleep(0.2)
# Sets the trigPin on HIGH state for 10 micro seconds
a.digitalWrite(trigPin, a.HIGH)
sleep(0.1)
a.digitalWrite(trigPin, a.LOW)
# Reads the echoPin, returns the sound wave travel time in microseconds
duration = a.pulseIn(echoPin, a.HIGH)
# Calculating the distance
distance = duration*0.034/2
# Prints the distance on the Serial Monitor
print("Distance: ")
print(distance)
while True:
loop()
The code above has been taken from a working Arduino example and transposed into Python and deployed on the master Raspberry Pi.
I have been looking at the nanpy docs, and it is not clear on how to achieve this and there are no tutorials on the internet on how to do this.
Has anyone got a working example of using the ultrasonic sensor and controlled through nanpy via a Raspberry Pi that they can share here and submit the code so I can get it working?
I have the following error with this code that a.pulseIn is not a function.
If pulseIn could be made to work the same as on an Arduino that would be ideal!
1 Answer 1
I have finally managed to get the Ultrasonic sensor working with Raspberry Pi and nanpy!
First, the python code to be executed on a Raspberry Pi:
from nanpy import ArduinoApi
from nanpy import SerialManager
from nanpy import Ultrasonic
from time import sleep
trigPin = 9
echoPin = 10
connection = SerialManager(device='/dev/ttyACM0')
a = ArduinoApi(connection=connection)
ultrasonic = Ultrasonic(echoPin, trigPin, False, connection=connection)
def test():
distance = ultrasonic.get_distance()
if distance < 5:
print('distance is:')
print(distance)
print('too close!')
sleep(0.002)
while True:
test()
For the circuit:
vcc on ultrasonic to 5V trig on ultrasonic to pin 9 Arduino echo on ultrasonic to pin 10 Arduino gnd on ultrasonic to ground
Before you run this code, you must install nanpy directly! Do not install it from pip as it is out of date and doesn't have the pulseIn function!
git clone https://github.com/nanpy/nanpy
cd nanpy
python3 setup.py install
This will add it to your python3 modules to use in projects.
Follow the project instructions on how to install the firmare:
https://github.com/nanpy/nanpy#user-content-how-to-build-and-install
Modify the cfg.h so Ultrasonic has a 1 next to it and not a 0
Upload the firmware as specified in the previous link.
Enjoy!
get_distance
orreading_in_range
github.com/nanpy/nanpy/blob/…