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!
get_distance
orreading_in_range
github.com/nanpy/nanpy/blob/…