SunFounder Thales Kit for Raspberry Pi Pico, Release 1.0
When the program runs, it will start counting and print the numbers in the shell. When we press the button, it will stop
counting and enter the callback function to print “You press the button!”.
Go back to the original example. We need to make the LED turn off in a random time of 5 to 10 seconds, which is
achieved by the following two lines:
import
machine
import
utime
import
urandom
led
=
machine
.
Pin(
15
, machine
.
Pin
.
OUT)
button
=
machine
.
Pin(
14
, machine
.
Pin
.
IN)
def
button_press
(pin):
button
.
irq(handler
=
None
)
rection_time
=
utime
.
ticks_diff(utime
.
ticks_ms(), timer_light_off)
(
"Your reaction time was "
+
str
(rection_time)
+
" milliseconds!"
)
led
.
value(
1
)
utime
.
sleep(urandom
.
uniform(
5
,
10
))
led
.
value(
0
)
timer_light_off
=
utime
.
ticks_ms()
button
.
irq(trigger
=
machine
.
Pin
.
IRQ_RISING, handler
=
button_press)
The
urandom
library is loaded here. Use the
urandom.uniform(5,10)
function to generate a random number,
the ‘uniform’ part referring to a uniform distribution between those two numbers.
If needed, try running the following example of random number generation:
import
machine
import
utime
import
urandom
while
True
:
(urandom
.
uniform(
1
,
20
))
utime
.
sleep(
1
)
The last two statements you need to understand are
utime.ticks_ms()
and
utime.ticks_diff()
.
import
machine
import
utime
import
urandom
led
=
machine
.
Pin(
15
, machine
.
Pin
.
OUT)
button
=
machine
.
Pin(
14
, machine
.
Pin
.
IN)
def
button_press
(pin):
button
.
irq(handler
=
None
)
rection_time
=
utime
.
ticks_diff(utime
.
ticks_ms(), timer_light_off)
(
"Your reaction time was "
+
str
(rection_time)
+
" milliseconds!"
)
led
.
value(
1
)
utime
.
sleep(urandom
.
uniform(
5
,
10
))
led
.
value(
0
)
timer_light_off
=
utime
.
ticks_ms()
button
.
irq(trigger
=
machine
.
Pin
.
IRQ_RISING, handler
=
button_press)
• The
utime.ticks_ms()
function will output the number of milliseconds that have passed since the
utime
library started counting and store it in the variable
timer_light_off
.
62
Chapter 3. For MicroPython User
Summary of Contents for Thales Kit
Page 1: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 Jimmy SunFounder Jun 04 2021 ...
Page 2: ......
Page 4: ...ii ...
Page 6: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 2 CONTENTS ...
Page 140: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 136 Chapter 3 For MicroPython User ...
Page 164: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 160 Chapter 4 For Arduino User ...