本文整理汇总了Python中pyb.Timer.callback方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.callback方法的具体用法?Python Timer.callback怎么用?Python Timer.callback使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyb.Timer
的用法示例。
在下文中一共展示了Timer.callback方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TimeThread
# 需要导入模块: from pyb import Timer [as 别名]
# 或者: from pyb.Timer import callback [as 别名]
class TimeThread(object):
"""
This class allows to make a call of several functions with a specified time
intervals. For synchronization a hardware timer is used. The class contains
main loop to check flags of queue.
"""
def __init__(self, timerNum, showExceptions = False):
self.showExceptions = showExceptions
self.timerQueue = []
self.timer = Timer(timerNum, freq=1000)
self.timer.callback(self._timer_handler)
"""
The method adds a pointer of function and delay time to the event queue.
Time interval should be set in milliseconds.
When the method adds to the queue it verifies uniqueness for the pointer.
If such a pointer already added to an event queue then it is not added again.
When the queue comes to this pointer then entry is removed from the queue.
But the pointer function is run.
"""
def set_time_out(self, delay, function):
b = True
for r in self.timerQueue:
if r[1] == function:
b = False
if b:
self.timerQueue += [[delay, function]]
# The handler of hardware timer
def _timer_handler(self, timer):
q = self.timerQueue
for i in range(len(q)):
if q[i][0] > 0:
q[i][0] -= 1
"""
The method runs an infinite loop in wich the queue is processed.
This method should be accessed after pre-filling queue.
Further work is performed within the specified (by the method
set_time_out()) functions.
"""
def run(self):
q = self.timerQueue
while True:
for i in range(len(q) - 1, -1, -1):
if q[i][0] == 0:
f = q[i][1]
del(q[i])
if self.showExceptions:
f()
else:
try:
f()
except Exception as e:
print(e)
示例2: UltraSonicMeter
# 需要导入模块: from pyb import Timer [as 别名]
# 或者: from pyb.Timer import callback [as 别名]
class UltraSonicMeter(object):
def __init__(self):
self.tmp = self.time = 0
self.cnt = 0
self.fr = 0
self.trig = Pin('X12', Pin.OUT_PP, Pin.PULL_NONE)
echoR = Pin('X1', Pin.IN, Pin.PULL_NONE)
echoF = Pin('X2', Pin.IN, Pin.PULL_NONE)
self.micros = pyb.Timer(5, prescaler=83, period=0x3fffffff)
self.timer = Timer(2, freq=1000)
self.timer.period(3600)
self.timer.prescaler(1375)
self.timer.callback(lambda e: self.run_trig())
extR = ExtInt(echoR, ExtInt.IRQ_RISING, Pin.PULL_NONE, self.start_count)
extF = ExtInt(echoF, ExtInt.IRQ_FALLING, Pin.PULL_NONE, self.read_dist)
def run_trig(self):
self.trig.high()
pyb.udelay(1)
self.trig.low()
def start_count(self, line):
self.micros.counter(0)
self.time = self.micros.counter()
self.timer.counter(0)
def read_dist(self, line):
end = self.micros.counter()
micros = end-self.time
distP1 = micros//5
distP2 = micros//6
distP3 = (distP1-distP2)//10*2
dist = distP2+distP3
if dist != 0:
self.cnt += 1
self.fr += dist
if self.cnt == 15:
tmp = self.tmp
dist = self.fr//self.cnt
if tmp != dist:
print(dist, 'mm')
self.tmp = dist
self.cnt = 0
self.fr = 0
示例3: align
# 需要导入模块: from pyb import Timer [as 别名]
# 或者: from pyb.Timer import callback [as 别名]
# set motor speed
motor1.set_speed(-controlspeed-int(300*cmd[0]))
motor2.set_speed(-controlspeed+int(300*cmd[0]))
pyb.udelay(5000-pyb.elapsed_micros(start))
# stop and turn off motors
motor1.set_speed(0)
motor2.set_speed(0)
motor1.set_off()
motor2.set_off()
# main program
lcd.clear()
lcd.text("IP: "+radio.getipaddr(),0,24,1)
lcd.display()
pyb.delay(3000)
while True:
align()
tim.callback(issr) #start interrupt routine
balance()
tim.callback(None) #stop interrupt routine
示例4: symbol
# 需要导入模块: from pyb import Timer [as 别名]
# 或者: from pyb.Timer import callback [as 别名]
key_last = 0
key_old = 0
key_flag = 0
key_buf = array.array('i', [0] * 25) # Room for 20 key presses/releases
# Constants
NONE = 0 # No key pressed
NEW = 3 # key_flag = 3 means it's debounced and New
USED = 4 # key_flag = 4 means consumer has received symbol (Not New anymore)
if __name__ == '__main__':
port_init() # Init PortC for keypad
tim = Timer(5, freq=100) # create a timer object using timer 5 - trigger at 50Hz
tim.callback(scan_timer_callback) # set the callback to keypad-scanner
# Todo: why do we sometimes get: 'scan_keys()' not defined? in the callback when Timer 4 or 5 is used ?
''' scan_keys: ['9', '9'] 521
uncaught exception in Timer(4) interrupt handler
NameError: name 'scan_keys' is not defined
scan_keys: ['7', '', '9', '5', '6', ''] 1285
Traceback (most recent call last):
File "test_keypad.py", line 48, in <module>
'''
fifo = FIFO(key_buf) # FIFO-object with global buffer
while True:
""" Since the consumer probably is slower than scan_keys, short key presses will be missed.
Debouncing is done in the callback as well as setting key_flag (status).
示例5: Stepper
# 需要导入模块: from pyb import Timer [as 别名]
# 或者: from pyb.Timer import callback [as 别名]
while pyb.millis() <= now + ms:
n = (n + 1) % 4
leds[n].toggle()
pyb.delay(50)
finally:
for l in leds:
l.off()
from nemastepper import Stepper
motor1 = Stepper('Y1','Y2','Y3')
from pyb import Timer
def step_cb(t):
motor1.do_step()
tim = Timer(8,freq=10000)
tim.callback(step_cb) #start interrupt routine
motor1.MAX_ACCEL = 1000
motor1.set_speed(1000)
disco(1000)
motor1.set_speed(0)
motor1.set_speed(-1000)
disco(1000)
motor1.set_speed(0)
motor1.set_off()
tim.deinit()
示例6: Timer
# 需要导入模块: from pyb import Timer [as 别名]
# 或者: from pyb.Timer import callback [as 别名]
import pyb
from pyb import Timer
tim = Timer(4)
tim = Timer(4, prescaler=100, period=200)
print(tim.prescaler())
print(tim.period())
tim.prescaler(300)
print(tim.prescaler())
tim.period(400)
print(tim.period())
tim = Timer(4, freq=1)
tim.init(freq=2000)
def f(t):
print(1)
t.callback(None)
tim.callback(f)
pyb.delay(10)
# f3 closes over f2.y
def f2(x):
y = x
def f3(t):
print(2, y)
t.callback(None)
return f3
tim.callback(f2(3))
pyb.delay(10)
示例7: tick
# 需要导入模块: from pyb import Timer [as 别名]
# 或者: from pyb.Timer import callback [as 别名]
# Timer Control Example
#
# This example shows how to use a timer for callbacks.
import time
from pyb import Pin, Timer
def tick(timer): # we will receive the timer object when being called
print("Timer callback")
tim = Timer(4, freq=1) # create a timer object using timer 4 - trigger at 1Hz
tim.callback(tick) # set the callback to our tick function
while (True):
time.sleep(1000)
示例8: __init__
# 需要导入模块: from pyb import Timer [as 别名]
# 或者: from pyb.Timer import callback [as 别名]
#.........这里部分代码省略.........
elif status == 0:
if self.HL.value() == 0:
self.TL.pulse_width_percent(0)
else:
self.TL.pulse_width_percent(self.low_light)
def Blink(self, side):
if side == -1:
self.RH.low()
if self.LH.value() == 0:
self.LH.high()
else:
self.LH.low()
if side == 1:
self.LH.low()
if self.RH.value() == 0:
self.RH.high()
else:
self.RH.low()
if side == 2:
if self.RH.value() == 0:
self.RH.high()
self.LH.high()
else:
self.RH.low()
self.LH.low()
if side == 0:
self.RH.low()
self.LH.low()
def mcallback(self, t):
self.step += 1
def MotorStatus(self, status):
if status == 1:
self.LH_STBY.high()
self.RH_STBY.high()
self.tim7.callback(self.mcallback)
elif status != 1:
self.LH_STBY.low()
self.RH_STBY.low()
self.tim7.callback(None)
def DoStep(self, dir_L, dir_R):
percent_A = self.power_L * math.sin(self.step_L * 2 * math.pi / self.n_steps)
percent_B = self.power_L * math.cos(self.step_L * 2 * math.pi / self.n_steps)
if percent_A > 0:
self.LH_AIN1.high()
self.LH_AIN2.low()
else:
self.LH_AIN1.low()
self.LH_AIN2.high()
percent_A *= -1
if percent_B > 0:
self.LH_BIN1.high()
self.LH_BIN2.low()
else:
self.LH_BIN1.low()
self.LH_BIN2.high()
percent_B *= -1
示例9: Encoder
# 需要导入模块: from pyb import Timer [as 别名]
# 或者: from pyb.Timer import callback [as 别名]
class Encoder():
"""
Abstracts a quadrature encoder to give a tick count.
The count is a signed integer starting at zero. It wraps the count from the
attached timer to give a seamless and continuous tick count. Overflows of
the internal timer counter register should be adequatly handled. If
overflows or weird behaviour occurs around the overflow points, try
increasing Encoder.HYSTERESIS.
Note: Only works on pin pairs 'X1' & 'X2', 'X9' & 'X10', or 'Y1', 'Y2'. The
timer will be automatically selected. Both Timer 2 and 5 work for 'X1' &
'X2', but Timer 5 is preferred because Timer 2 is used for LED PWM but both
can be used by changing the values of Encoder.AF_MAP.
"""
# Constant for decoding in single line mode
SINGLE_MODE = Timer.ENC_A
# Constant for decoding in quad mode
DUAL_MODE = Timer.ENC_AB
# Maps alternate pin function descriptions to the required timer number
TIMER_MAP = {'AF1_TIM2': 2, 'AF2_TIM4': 4, 'AF2_TIM5': 5, 'AF3_TIM8': 8}
# Maps pin names to the alternate function to use
AF_MAP = {'X1' : 'AF2_TIM5', 'X2': 'AF2_TIM5', 'X9': 'AF2_TIM4',
'X10': 'AF2_TIM4', 'Y1': 'AF3_TIM8', 'Y2': 'AF3_TIM8'}
# Defines the pin pairs that must be used
PIN_PAIRS = [['X1','X9','Y1'],['X2','X10','Y2']]
# Hysteresis value to overflow detection
HYSTERESIS = 12 # One full rotation of encoder
def __init__(self, pinA, pinB, mode = DUAL_MODE):
"""
Instantiate an Encoder object.
Initalises the Pins, Timer and TimerChannel for use as a quadrature
decoder. Registers an overflow callback to elegantly handle counter
register overflows.
pinA: Any valid value taken by pyb.Pin constructor
pinB: Any valid value taken by pyb.Pin constructor
mode: Mode to use for decoding (Encoder.SINGLE_MODE or
Encoder.DUAL_MODE)
raises: Any exception thrown by pyb.Pin, pyb.Timer, pyb.Timer.channel
or Exception if pins are not compatible pairs
"""
self._chA = Pin(pinA)
self._chB = Pin(pinB)
self._ticks = 0
# Check pins are compatible
self._checkPins(pinA, pinB)
# init pins for alternate encoder function
af = self.AF_MAP[self._chA.names()[1]]
channel = self.TIMER_MAP[af]
af = getattr(Pin, af)
self._chA.init(Pin.AF_PP, pull = Pin.PULL_NONE, af = af)
self._chB.init(Pin.AF_PP, pull = Pin.PULL_NONE, af = af)
# init timer
self._timer = Timer(channel, prescaler = 0, period = 100000)
# init encoder mode
# self._channel = self._timer.channel(1, mode)
self._timer.channel(1, mode)
# setup overflow callback
self._timer.callback(self._overflow)
# init count register to middle of count
self._timer.counter(self._timer.period()//2)
self._lastRead = self._timer.counter()
def _checkPins(self, pinA, pinB):
"""
Check that two pins can be used for a decoding and are on the same
timer.
"""
try:
if pinA in self.PIN_PAIRS[0]:
if self.PIN_PAIRS[0].index(pinA) != self.PIN_PAIRS[1].index(pinB):
raise Exception()
elif pinA in self.PIN_PAIRS[1]:
if self.PIN_PAIRS[0].index(pinB) != self.PIN_PAIRS[1].index(pinA):
raise Exception()
else:
raise Exception()
except:
raise Exception(pinA + ' & ' + pinB + ' are not on the same Timer')
def ticks(self, ticks = None):
"""
Get or set the current tick count.
Ticks is a signed integer.
"""
if ticks is not None: # set ticks to desired value
self._ticks = ticks
else: # retrieve latest count and update internals
count = self._timer.counter()
self._ticks = self._ticks + (count - self._lastRead)
self._lastRead = count
return self._ticks
def _overflow(self, timer):
"""
Timer overflow callback to gracefully handle overflow events. If
weird things are occurring, try increasing the HYSTERESIS value.
"""
count = timer.counter()
#.........这里部分代码省略.........
示例10: return
# 需要导入模块: from pyb import Timer [as 别名]
# 或者: from pyb.Timer import callback [as 别名]
else:
return (sensor.read()/2552.3)**(1/-1.045)
# decrease volume as object gets closer
def v_change_dis():
return 255-int((sensor.read()) >> 4)
# you can get rid of "255-" to make it do the opposite
# volume control
tim = Timer(1)
tim.init(freq=20)
dac = DAC(1)
pot = ADC('B0')
# tim.callback(lambda t: dac.write(int(pot.read()>>4)))
tim.callback(lambda t: dac.write(v_change_dis()))
# GPIO test
gpio = pyb.Pin('A13', pyb.Pin.OUT_PP)
gpio.high()
pyb.delay(10)
gpio.low()
pyb.delay(10)
gpio.high()
pyb.delay(10)
'''
class stat:
def __init__(self):
self.s = 0
def num(self):
self.s = 14
示例11: cb2
# 需要导入模块: from pyb import Timer [as 别名]
# 或者: from pyb.Timer import callback [as 别名]
def cb2(t):
print("cb2")
t.deinit()
# callback where cb4 closes over cb3.y
def cb3(x):
y = x
def cb4(t):
print("cb4", y)
t.callback(None)
return cb4
# create a timer with a callback, using callback(None) to stop
tim = Timer(1, freq=1000, callback=cb1)
pyb.delay(10)
# create a timer with a callback, using deinit to stop
tim = Timer(2, freq=1000, callback=cb2)
pyb.delay(10)
# create a timer, then set the freq, then set the callback
tim = Timer(4)
tim.init(freq=2000)
tim.callback(cb1)
pyb.delay(10)
# test callback with a closure
tim.init(freq=3000)
tim.callback(cb3(3))
pyb.delay(10)