# Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time , micropython
from pyb import Pin, Timer, LED
blue_led = LED(3)
# we will receive the timer object when being called
# Note: functions that allocate memory are Not allowed in callbacks
def tick(timer):
blue_led.toggle()
print('-T2 out-')
tim = Timer(2, freq=1)
tim.prescaler(10) #10 seconds
tim.callback(tick)
Timeout_counter=0
while (True):
time.sleep_ms(1000)
Timeout_counter+=1
print('Timeout_counter=%d' %Timeout_counter)
the result is following:----------
Timeout_counter=1
-T2 out-
Timeout_counter=2
Timeout_counter=3
Timeout_counter=4
Timeout_counter=5
Timeout_counter=6
Timeout_counter=7
Timeout_counter=8
Timeout_counter=9
Timeout_counter=10
Timeout_counter=11
Timeout_counter=12
-T2 out-
Timeout_counter=13
Timeout_counter=14
Timeout_counter=15
Timeout_counter=16
Timeout_counter=17
Timeout_counter=18
Timeout_counter=19
Timeout_counter=20
Timeout_counter=21
Timeout_counter=22
Timeout_counter=23
-T2 out-
Timeout_counter=24
Timeout_counter=25
Timeout_counter=26
/----------------------------------------/
code print T2 out every 10 second . it is ok.
my code is following:
# Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time , micropython
from pyb import Pin, Timer, LED
blue_led = LED(3)
# we will receive the timer object when being called
# Note: functions that allocate memory are Not allowed in callbacks
def tick(timer):
global tim
blue_led.off()
print('timeout-off')
tim.deinit()#<---------------
tim = Timer(2, freq=1) # create a timer object using timer 2 - trigger at 1Hz
tim.prescaler(10)
tim.callback(tick) # set the callback to our tick function
Timeout_counter=0
while (True):
time.sleep_ms(1000)
Timeout_counter+=1
print('Timeout_counter=%d' %Timeout_counter)
if Timeout_counter==3:
print('3s-on')
blue_led.on()
tim = Timer(2,freq=1)#<---------------
tim.prescaler(10)#<---------------
tim.callback(tick)##<---------------
if Timeout_counter==15:
Timeout_counter=0
print('15s')
now the result:------------
Timeout_counter=1
timeout-off
Timeout_counter=2
Timeout_counter=3
3s-on
Timeout_counter=4
timeout-off
Timeout_counter=5
Timeout_counter=6
Timeout_counter=7
Timeout_counter=8
Timeout_counter=9
Timeout_counter=10
Timeout_counter=11
Timeout_counter=12
Timeout_counter=13
Timeout_counter=14
Timeout_counter=15
15s
Timeout_counter=1
Timeout_counter=2
Timeout_counter=3
3s-on
Timeout_counter=4
timeout-off
Timeout_counter=5
Timeout_counter=6
Timeout_counter=7
Timeout_counter=8
Timeout_counter=9
‘’’
the timer2 print “timeout-off” after 1 second ,not 10 second.
what is wrong with my code?