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:
(e)
while
True
:
distance
=
sonar
.
read()
(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:
(e)
while
True
:
distance
=
sonar
.
read()
(distance)
(continues on next page)
70
Chapter 4. Play with Python
Summary of Contents for PiSloth
Page 1: ...SunFounder pisloth www sunfounder com Oct 19 2021 ...
Page 2: ......
Page 4: ...ii ...
Page 6: ...SunFounder pisloth 2 CONTENTS ...
Page 8: ...SunFounder pisloth 4 Chapter 1 Component List and Assembly Instructions ...
Page 18: ...SunFounder pisloth EXAMPLE 14 Chapter 3 Play with Ezblock ...
Page 20: ...SunFounder pisloth 16 Chapter 3 Play with Ezblock ...
Page 22: ...SunFounder pisloth Confuse Happy 18 Chapter 3 Play with Ezblock ...
Page 23: ...SunFounder pisloth Fear Sad 3 5 Emotional PiSloth 19 ...
Page 25: ...SunFounder pisloth 3 6 Dance Now PiSltoh will show you his newly learned dance 3 6 Dance 21 ...
Page 28: ...SunFounder pisloth 24 Chapter 3 Play with Ezblock ...
Page 32: ...SunFounder pisloth 28 Chapter 3 Play with Ezblock ...
Page 35: ...SunFounder pisloth 3 8 Remote Control 31 ...
Page 39: ...SunFounder pisloth 3 9 Custom Step 35 ...
Page 41: ...SunFounder pisloth The complete code is as follows 3 9 Custom Step 37 ...
Page 50: ...SunFounder pisloth Step 7 Click the WRITE button 46 Chapter 4 Play with Python ...
Page 86: ...SunFounder pisloth 82 Chapter 4 Play with Python ...
Page 90: ...SunFounder pisloth Yes then Ok Finish 86 Chapter 5 Appendix ...
Page 94: ...SunFounder pisloth Step 4 Double click the connection just created 90 Chapter 5 Appendix ...
Page 102: ...SunFounder pisloth 98 Chapter 5 Appendix ...