SunFounder pisloth
(continued from previous page)
sloth.set_offset([0,0,0,0])
sonar = Ultrasonic(Pin("D2") ,Pin("D3"))
alert_distance = 10
def main():
distance = sonar.read()
if distance < 0:
pass
elif distance <= alert_distance:
try:
music.sound_effect_threading('./sounds/sign.wav')
except Exception as e:
print(e)
sloth.do_action('hook', 1,95)
time.sleep(0.5)
sloth.do_action('stand', 1,95)
time.sleep(0.5)
sloth.do_action('turn left',7,90)
sloth.do_action('stand', 1,95)
time.sleep(0.2)
else :
sloth.do_action('forward', 1,90)
if __name__ == "__main__":
while True:
main()
How it works?
You can get the distance by importing the Ultrasonic class.
from robot_hat import Ultrasonic
Then initialize the ultrasonic pins.
sonar = Ultrasonic(Pin("D2") ,Pin("D3"))
Here is the main program.
• Read the distance detected by ultrasonic module and filter out the values less than 0 (When the ultrasonic
module is too far from the obstacle or cannot read the data correctly, distance<0 will appear).
• When the distance is less than or equal to alert_distance (the threshold value set earlier, which is 10),
play the sound effect sign.wav. PiSloth does hook, stand, left turn and stand in sequence.
• When the distance is greater than alert_distance, PiSloth will move forward.
distance = sonar.read()
if distance < 0:
pass
elif distance <= alert_distance:
try:
music.sound_effect_threading('./sounds/sign.wav')
except Exception as e:
print(e)
sloth.do_action('hook', 1,95)
(continues on next page)
84 Chapter 4. Play with Python