EasyManua.ls Logo

SunFounder PiSloth - Page 92

SunFounder PiSloth
113 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
SunFounder pisloth
(continued from previous page)
music = Music()
sloth = Sloth([1,2,3,4])
sloth.set_offset([0,0,0,0])
sonar = Ultrasonic(Pin("D2") ,Pin("D3"))
alert_distance = 40
contact_distance = 5
def main():
distance = sonar.read()
if distance <= alert_distance and distance >= contact_distance :
try:
music.sound_effect_play('./sounds/battle.wav')
music.background_music('./musics/attack.mp3')
music.music_set_volume(20)
except Exception as e:
print(e)
while True:
distance = sonar.read()
print(distance)
if distance < 0:
continue
if distance <= contact_distance:
break
sloth.do_action('forward', 1,90)
sloth.do_action('stand', 1, 90)
time.sleep(1)
if __name__ == "__main__":
while True:
main()
How it works?
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 between 5 and 40, PiSloth will play warning.wav and attack.mp3 and move
forward.
When the distance is less than 5, PiSloth will keep the stand position.
distance = sonar.read()
if distance <= alert_distance and distance >= contact_distance :
try:
music.sound_effect_play('./sounds/battle.wav')
music.background_music('./musics/attack.mp3')
music.music_set_volume(20)
except Exception as e:
print(e)
while True:
distance = sonar.read()
print(distance)
(continues on next page)
88 Chapter 4. Play with Python

Related product manuals