def main(): # Configure timer2 as a microsecond counter. tim = Timer(config["timer"], prescaler=(machine.freq()[0] // 1000000) - 1, period=config["timer-period"]) tim2 = Timer(config["led-timer"], freq=config["led-freq"]) tim2.callback(lambda t: pyb.LED(config["led-id"]).toggle()) # Configure channel for timer IC. ch = tim.channel(1, Timer.IC, pin=config["pin-capture"], polarity=Timer.FALLING) # Slave mode disabled in order to configure mem32[config["timer-addr"] + TIM_SMCR] = 0 # Reset on rising edge (or falling in case of inverted detection). Ref: 25.4.3 of STM32F76xxx_reference_manual.pdf mem32[config["timer-addr"] + TIM_SMCR] = (mem32[config["timer-addr"] + TIM_SMCR] & 0xfffe0000) | 0x54 # Capture sensitive to rising edge. Ref: 25.4.9 of STM32F76xxx_reference_manual.pdf mem32[config["timer-addr"] + TIM_CCER] = 0b1011 print("capturing") capture(ch)
def main(): ## 创建测试磁场对象,统一分配引脚 tiny = pyb.Pin('X1', pyb.Pin.OUT_PP) # 对应小电阻, 接CM1 big = pyb.Pin('X2', pyb.Pin.OUT_PP) # 对应大电阻, 接CM2 rw = resistSwitch(big_resist_pin=big, tiny_resist_pin=tiny) bufs = generate_bufs() record_sig = syncSignal(pyb.Pin('X3', pyb.Pin.OUT_PP)) # X3 对应光耦IN1 sync_sig = syncSignal(pyb.Pin('X4', pyb.Pin.OUT_PP)) # X4 对应光耦IN2 freqs = [10] ch = 1 # X5 标定磁场输出 repeat = 20 timer_num = 6 mctrl = magCtrl(bufs, freqs, ch, sync_sig, rw, repeat, timer_num) record_sig.falling_edge() # 发送启动记录的信号 led = ledCue() ## timer3,用于循环测试 tim3 = Timer(3) tim3.init(freq=0.1) tim3.callback(mctrl.next) while not mctrl.end_flg: if mctrl.new_block: led.next(mctrl.stimulus_typ) mctrl.new_block = False time.sleep_us(500000) # 每50ms record_sig.falling_edge() # 发送结束记录的信号 led.end()
def runLedStartNoBlock(flag=True, tim_num=14, tim_freq=0.3, led_num=4): """ """ if flag: tim = Timer(tim_num, freq=tim_freq) tim.callback(lambda cb_fun: LED(led_num).toggle()) else: pass
def main(): ## 统一分配引脚 bc = BoardCtrl('X1', 'X2', 'X3', 'X4') bufs = generate_bufs() DAC_ch = 'X5' sync_sig = syncSignal('X6') # record_sig = syncSignal('X7') freqs = [13] repeat = 1 timer_num = 6 mctrl = magCtrl(bufs, freqs, DAC_ch, sync_sig, bc, repeat, timer_num) # record_sig.falling_edge() # 发送启动记录的信号 led = ledCue() ## timer3,用于循环测试 tim3 = Timer(3) tim3.init(freq=0.2) tim3.callback(mctrl.next) while not mctrl.end_flg: if mctrl.new_block: led.next(mctrl.stimulus_level) mctrl.new_block = False time.sleep_us(500000) # 每50ms # record_sig.falling_edge() # 发送结束记录的信号 led.end()
class SPWM(): def __init__(self, freq=100): self.pwm_pin = Pin('PA5', Pin.OUT) self.pwm_tim = Timer(2) #not start self.flag = 0 self.pp = 50 def start(self): self.pwm() self.modulate() while 1: if self.flag: self.flag = 0 #计算self.pp 占空比 #配置pwm占空比 self.ch.pulse_width_percent(self.pp) def pwm(self, enable=True): self.pwm_tim = Timer(2, freq=10000) self.ch = self.pwm_tim.channel(1, Timer.PWM, pin=self.pwm_pin) self.ch.pulse_width_percent(50) def modulate(self, freq_m=10): self.m_tim = Timer(5, freq=freq_m) self.m_tim.callback(lambda t: self.change()) def change(self): self.flag = 1
def __init__(self): # self.LFront = SpiderLimbs(0, 1, 2) # self.RFront = SpiderLimbs(4, 5, 6) # self.LRear = SpiderLimbs(8, 9, 10) # self.RRear = SpiderLimbs(12, 13, 14) self.ready() tim = Timer(1, freq=2) tim.callback(self.actionIRQ)
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)
def main(): pwm_timer = Timer(MOTOR_TIMER, freq=PWM_FREQ) ch1 = motorController(PIN_CH1, pwm_timer, 1) ch2 = motorController(PIN_CH2, pwm_timer, 2) adc = ADC(PIN_ADC) main_loop = loop(adc, ch1, ch2) event_timer = Timer(EVENT_TIMER, freq=1000) event_timer.freq(10) event_timer.callback(lambda t: next(main_loop))
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): 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]) try: f() except: pass
def main(): # 2 Hz timer # Timer( Timer#, freq ) TIM1 = Timer(1, freq=2) # get/set frequency (of your timer instance) # this is probably what you want to set # TIM1.freq(5) # Can set non-integer frequencies too! # TIM1.freq(0.3) # TIM1.freq(1.5) # Set callback function run on each counter tick: # TIM1.callback(lambda t: pyb.LED(1).toggle) # TIM1.callback( lambda x: your_function() ) # Timer callback functions need to have a parameter to accept the timer if you want to set them as the callback without a lambda # eg: # TIM1.callback( do_stuff ) # # requires: # def do_stuff( timer ): # ...do something... # # def do_stuff(): # ..... # will not work! # Timer callbacks are interrupt handlers # And are not allowed to allocate memory! # Memory allocation can be surprising # eg, # for item in data # this is memory allocation! (of an iterator) # you will get a 'heap locked' error # the proper way is to do: # for i range(0, len(data)) # item = data[i] # Clear callback: # TIM1.callback(None) # delete timer, callback, and any channel callbacks # TIM1.deinit() # or even # Timer(1).deinit() # 2Hz led flash TIM1.callback(lambda x: toggleLED1())
class PidTimer(Pid): ''' Implements the PID-stabilization algorithm as a Timer callback IMPORTANT!!! It seems it is not allowed to allocate memory within the timer callback. Therefore, this class won't work. ''' def __init__(self, timerId, length, readInputDelegate, setOutputDelegate, pidName): ''' Constructor @param timerId: Timer to be used @param length: Number of items to stabilize @param readInputDelegate: Method to gather current values. Must return an array with the same number of items to stabilize @param setOutputDelegate: Delegate's parameter is an array with the values to react, one for each item to stabilize. @param pidName: (optional) Name to identify the PID-thread among other ones. ''' super().__init__(length, readInputDelegate, setOutputDelegate, pidName) self._timer = Timer(timerId) def _doCalculate(self, timer): print("_doCalculate") self._calculate() def init(self, freq, initRunning=True): ''' Initializes stabilization as a coroutine. Initializes a thread to perform calculations in background @param freq: Frequency of the stabilization. This value is ignored if period is provided @param initRunning: Starts stabilization immediately ''' self._timer.init(freq=freq) self._timer.callback(lambda t: self._doCalculate(t)) def stop(self): ''' Stops the coroutine ''' self._timer.callback(None) self._timer.deinit()
class MCU(object): # LED led(1)=green, led(2)=blue, led(3)=yellow, led(4)=red # leds [0=green, 1=blue, 2=yellow, 3=red] colors = ('green', 'blue', 'yellow', 'red') mode = ('deterministic', 'random') def __init__(self): self._timer = Timer(8, freq=1) self._leds = [LED(i) for i in range(1, 5)] self._color = 'yellow' self._timer.callback(self._callback_) self._mode = False #'deterministic' self._led = self._leds[0] self._status = False def _callback_(self, tim): self._status = False if self._status else True id = randint(0,3) if self._mode is True \ else self.colors.index(self._color) led = self._leds[id] if led != self._led: self._led.off() self._led = led self._led.on() if self._status else self._led.off() def _set_color(self, color): if self._color != color: n = self.colors.index(self._color) self._leds[n].off() self._color = color def yellow(self): self._set_color('yellow') def green(self): self._set_color('green') def blue(self): self._set_color('blue') def red(self): self._set_color('red') def random(self, mode=True): status = disable_irq() self._mode = mode enable_irq()
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
def main(): pwm_timer = Timer(MOTOR_TIMER, freq=PWM_FREQ) ch1 = motorController(PIN_CH1, pwm_timer, 1) ch2 = motorController(PIN_CH2, pwm_timer, 2) ch3 = motorController(PIN_CH3, pwm_timer, 3) ch4 = motorController(PIN_CH4, pwm_timer, 4) adc = ADC(PIN_ADC) pb_in = Pin(PIN_PB_H, Pin.IN, Pin.PULL_UP) pb_out = Pin(PIN_PB_L, Pin.OUT_PP) pb_out.low() main_loop = loop(adc, ch1, ch2, ch3, ch4, pb_in) event_timer = Timer(EVENT_TIMER, freq=1000) event_timer.freq(10) event_timer.callback(lambda t: next(main_loop))
def main(): # Configure the timer as a microsecond counter. tim = Timer(config["timer"], prescaler=(machine.freq()[0] // 1000000) - 1, period=config["timer-period"]) print(tim) # Configure timer for led blinking if "led-id" in config: timLed = Timer(config["led-timer"], freq=config["led-freq"]) timLed.callback(lambda t: LED(config["led-id"]).toggle()) # Configure channel for timer IC. ch = tim.channel(1, Timer.IC, pin=config["pin-capture"], polarity=Timer.FALLING) # Slave mode disabled in order to configure mem32[config["timer-addr"] + TIM_SMCR] = 0 # Reset on rising edge (or falling in case of inverted detection). Ref: 25.4.3 of STM32F76xxx_reference_manual.pdf mem32[config["timer-addr"] + TIM_SMCR] = (mem32[config["timer-addr"] + TIM_SMCR] & 0xfffe0000) | 0x54 # Capture sensitive to rising edge. Ref: 25.4.9 of STM32F76xxx_reference_manual.pdf # The same values are also valid for the MCU STM32L4x6 mem32[config["timer-addr"] + TIM_CCER] = 0b1001 motor = Motor(config["motor-pwm-pin"], config["motor-timer"], config["motor-channel"], config["motor-reverse-pin"]) try: testMotor(ch, motor, 10, 15) testMotor(ch, motor, 20, 15) testMotor(ch, motor, 40, 15) testMotor(ch, motor, 60, 15) testMotor(ch, motor, 80, 15) finally: motor.cleanup() timLed.deinit()
def main(): ## 预生成待测试的DAC序列 m = magGen() m.reset_param(radius=11.34) bufs = [] m.reset_param(resist=1100) #1.1MOhm 磁场范围约为50pT for s in [10, 20, 30, 40, 50]: buf = m.gen_ay(s) bufs.append((s, 'bigmag', buf)) bufs.append((0, 'cut', array('H', [0]))) m.reset_param(resist=9300) #9.3MOhm 磁场范围约为5pT for s in [1, 2, 3, 4, 5]: buf = m.gen_ay(s) bufs.append((s, 'tinymag', buf)) bufs.append((0, 'cut', array('H', [0]))) ## 创建测试磁场对象,统一分配引脚 tiny = pyb.Pin('X1', pyb.Pin.OUT_PP) # 对应小电阻, 接CM1 big = pyb.Pin('X2', pyb.Pin.OUT_PP) # 对应大电阻, 接CM2 rw = resistSwitch(big_resist_pin=big, tiny_resist_pin=tiny) sport = pyb.Pin('X3', pyb.Pin.OUT_PP) # 对应光耦IN1 sync = syncSignal(sport) freqs = [5, 13] ch = 1 # 对应X5 repeat = 2 timer_num = 6 mctrl = magCtrl(bufs, freqs, ch, sync, rw, repeat, timer_num) # timer3,用于循环测试 tim3 = Timer(3) tim3.init(freq=0.2) tim3.callback(mctrl.next)
class encoder(): # Period value is inclusive. counter will have max value == period # Only use channel 1 a and 2 of timer, and never 1N and 2N def __init__(self, pin_number_a, pin_number_b, period, timer_number): # Timer registers, needed for direction regs = [ 0, stm.TIM1, stm.TIM2, stm.TIM3, stm.TIM4, stm.TIM5, stm.TIM6, stm.TIM7, stm.TIM8, stm.TIM9, stm.TIM10, stm.TIM11, stm.TIM12 ] self.direction_register = regs[timer_number] + stm.TIM_CR1 # Pins pin_a = Pin(pin_number_a, Pin.IN) # PE9 pin_b = Pin(pin_number_b, Pin.IN) # PE11 # Encoder self.encoder = Timer(timer_number, prescaler=0, period=period) self.encoder.channel(1, Timer.ENC_AB, pin=pin_a) self.encoder.channel(2, Timer.ENC_AB, pin=pin_b) self.period = period self.rollover = 0 self.encoder.callback(self.loop_counter_rollover) def loop_counter_rollover(self, timer): if self.get_direction() == 0: self.rollover = self.rollover + 1 else: self.rollover = self.rollover - 1 def get_degrees(self): return 360.0 * self.encoder.counter( ) / self.period # encoder period is inclusive def get_degrees_total(self): return self.rollover * 360.0 + self.get_degrees() def get_direction(self): return (stm.mem32[self.direction_register] & 0x10) >> 4
yaw_angle = 0 out_str1 = '' clock = time.clock() #帧率 old_img = sensor.snapshot().mean_pooled(4, 4) # 160x120 -> 40x30,前一张照片 #定义一个定时发送数据的函数 def tick(timer): #we will receive the timer object when being called global flag flag = 1 tim = Timer(4, freq=20) # create a timer object using timer 4 - trigger at 1Hz tim.callback(tick) # set the callback to our tick function #--------------------------------------while循环开始-----------------------------------------# while (True): pyb.LED(1).on() if (flag == 1): img = sensor.snapshot() img_old = img.copy() img.lens_corr(1.5) # for 2.8mm lens...摄像头畸变纠正 #--------------------------------------光流定点-----------------------------------------# old = sensor.alloc_extra_fb(16, 16, sensor.GRAYSCALE) old.replace(sensor.snapshot().mean_pooled(4, 4)) new_img = sensor.snapshot().mean_pooled(4, 4) displacement = old.find_displacement(new_img) old_img.replace(new_img) delta_x0 = int(displacement.x_translation() * 5) / 5.0
def tick_response(self, _): """ Sample ADC input to set new target if necessary, then increment current value towards target. Scales current value and sets PWM percentage. """ adc_val = self.adc.read() if adc_val < ADC_MIN: adc_val = ADC_MIN if adc_val > ADC_MAX: adc_val = ADC_MAX demand = (adc_val - ADC_MIN) / ADC_RANGE print(self.target - demand) if abs(self.target - demand) > D_DELTA: print(self.target, demand, self.current) self.target = demand gap = demand - self.current self.increment = INCREMENT if gap > 0 else -INCREMENT self.ticks_left = int(gap / self.increment) if self.ticks_left: self.ticks_left -= 1 self.current += INCREMENT print(self.ticks_left) self.ch.pulse_width_percent(100 * self.current * self.current) d = DimmerLamp() TICK_TIMER.callback(d.tick)
import time from pyb import LED from pyb import Timer led = LED(1) led.on() #绑定事件方式1 def led_on_off(): global led #向全局寻求led变量 led.toggle() #反转led timer = Timer(4) #设置定时器4 timer.init(freq=1) #设置定时器频率:1s执行几次 timer.callback(lambda t: led_on_off()) #定时器中断函数/回调函数 while (True): #其后必须有语句体 time.sleep(1000) #绑定事件方式2 ''' def led_on_off(timer):#不同! global led#向全局寻求led变量 led.toggle()#反转led timer=Timer(4)#设置定时器4 timer.init(freq=1)#设置定时器频率:1s执行几次 timer.callback(led_on_off)#定时器中断函数/回调函数。不同! while(True):#其后必须有语句体 time.sleep(1000)
def clear_ecran(): uart.write("\x1b[2J\x1b[?25l") clock_time = 0 def clock(timer): global clock_time clock_time += 1 t = Timer(4, freq=10) t.callback(clock) def borders(): move(X_Left, Y_Top) uart.write("#" * (X_Right - X_Left)) move(X_Left, Y_Bottom) uart.write("#" * (X_Right - X_Left)) for y in range(Y_Top, Y_Bottom): move(X_Left, y) uart.write("#") move(X_Right, y) uart.write("#") def colision_left():
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
# 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)
class motor_with_encoder(): def __init__(self, motor, encoder, loop_timer_number): # loop_timer_number TIMn self.motor = motor self.encoder = encoder self.state_org = state_organizer() self.init_loop_timer(loop_timer_number) # Set an unused timer number, the values are based on a timer freq of 108MHz def init_loop_timer(self, timer_number): self.rollover = 0 self.loop_timer_period = 0xffff self.loop_timer = Timer( timer_number, prescaler=10800, period=self.loop_timer_period) # timer fq = 10000Hz 1s = 10000 self.loop_timer.callback(self.loop_counter_rollover) def loop_counter_rollover(self, timer): self.rollover = self.rollover + 1 # loop timer in milli seconds def get_loop_timer_ms(self): ctr = self.loop_timer.counter( ) + self.rollover * self.loop_timer_period return ctr / 10 # loop timer in seconds def get_loop_timer_s(self): ctr = self.loop_timer.counter( ) + self.rollover * self.loop_timer_period return ctr / 10000 def reset_loop_timer(self): self.rollover = 0 self.loop_timer.counter(0) def get_deg_error(self, deg_set, deg): err = deg_set - deg if err < -180: # 0 - 300 = -300 -> 60 err = err + 360 elif err > 180: # 270 - 30 = 240 -> -120 err = err - 360 return err def set_position(self, deg_set, k_p, k_i, acceptable_error=0.05): # timer = Timer(12, prescaler=10800, period=0xffff) #timer fq = 10000Hz 1s = 10000 _I = 0 # I@t-1 a = 0 err_prev = 999 _t = self.get_loop_timer_s() while True: a = a + 1 if a > 1000: print('Error: ', err, 'Power: ', power, 'K: ', K, 'I: ', I, 'Degrees: ', self.encoder.get_degrees()) a = 0 # asyncio.sleep(0.001) #Loop time is 1ms time.sleep_us(1000) t = self.get_loop_timer_s() dt = t - _t self.reset_loop_timer() deg = self.encoder.get_degrees() err = self.get_deg_error(deg_set, deg) if abs(err) < acceptable_error: err = 0 if err == err_prev: print('Final Error: ', err, 'Power: ', power, 'K: ', K, 'I: ', I, 'Degrees: ', self.encoder.get_degrees()) return err_prev = err I = dt * err + _I # Integrator # Cap integrator if I > 5: I = 5 elif I < -5: I = -5 _I = I K = err # Proportional power = k_p * K + k_i * I self.motor.set_power(power) _t = t # returns the average velocity since the last call def get_angular_velocity(self): # try this: https://docs.micropython.org/en/v1.9.3/pyboard/reference/speed_python.html#caching-object-references vel = self.state_org.vel # requires fewer object lookups time = self.get_loop_timer_s() position = self.encoder.get_degrees_total() dPosition = position - vel._pos dt = time - vel._time vel._pos = position vel._time = time return dPosition / dt def set_velocity(self, vel_set, k_p, k_i, loop_time_us=1000, filter_val=1): _v = self.get_angular_velocity() a = 0 _t = self.get_loop_timer_s() _I = 0 _vel = 0 while True: a = a + 1 if a > 200: print('v filter: ', v, 'Velocity: ', vel_act, 'Error: ', err, 'Power: ', power, 'K: ', K, 'I: ', I, '\n') a = 0 time.sleep_us(loop_time_us) t = self.get_loop_timer_s() dt = t - _t vel_act = self.get_angular_velocity() v = vel_act * filter_val + _v * (1 - filter_val) err = vel_set - v I = dt * err + _I # Integral K = err # Proportional power = k_p * K + k_i * I self.motor.set_power(power) _t = t _I = I _v = v
# 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
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).
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)
print(temperature) print(humidity) dustDriver.wakeup() try: rr = dustDriver.read() print(str(rr)) except IncorrectData: print('bad data') finally: dustDriver.sleep() workLed.off() freq = 1 / 8 # once per 100s tim = Timer(1, freq=freq) tim.callback(lambda _: micropython.schedule(do_work, 0)) # --------- SOUND ------------------------------------------------------------ avgSound = 0 n = 1 overNoisedCount = 0 noiseLevel = 0 def senseNoise(t): global n, noiseLevel, overNoisedCount noiseLed.toggle() val = pinNoiseThreshold.value() if val == 0: # 0 = overnoise overNoisedCount += 1 # noiseLevel = noiseLevelADC.read() # read value, 0-4095
class Robot: def __init__(self): # Timer for motor PWM self.tim2 = Timer(2, freq=10000) # Timer to dim lights self.tim4 = Timer(4, freq=1000) # Timer for motion self.tim7 = Timer(7, freq=800) # Variables self.step_R = 0 #counter for (micro) step self.step_L = 0 #counter for (micro) step self.step = 0 #counter for motion interrupt self.n_steps = 64 #number of steps self.dir_R = 0 #direction 1=positive, -1=negative, 0=none self.dir_L = 0 #direction 1=positive, -1=negative, 0=none self.speed_R = 0 #speed counter. If >255 step will be executed self.speed_L = 0 #speed counter. If >255 step will be executed self.max_speed_R = 256 #maximum speed self.max_speed_L = 256 #maximum speed self.sspeed_R = 0 #set speed self.sspeed_L = 0 #set speed self.dist_R = 0 #distance counter self.dist_L = 0 #distance counter self.power_R = 0 #PWM power setting 0 - 100% self.power_L = 0 #PWM power setting 0 - 100% self.low_light = 20 #PWM setting for tail light self.target_R = 0 #motion control position target self.target_L = 0 #motion control position target self.acc = 1 #motion control acceleration self.dts_R = 0 #motion distance to stop self.dts_L = 0 #motion distance to stop self.move = 0 #move motors or not # Lights: self.LH = Pin('PD12', pyb.Pin.OUT_PP) self.RH = Pin('PD13', pyb.Pin.OUT_PP) self.TL = self.tim4.channel(3, Timer.PWM, pin=Pin.cpu.D14) self.HL = Pin('PD15', pyb.Pin.OUT_PP) # RH Motor self.RH_STBY = Pin('PE6', pyb.Pin.OUT_PP) self.RH_PWMA = self.tim2.channel(1, Timer.PWM, pin=Pin.cpu.A15) self.RH_AIN1 = Pin('PE8', pyb.Pin.OUT_PP) self.RH_AIN2 = Pin('PE9', pyb.Pin.OUT_PP) self.RH_PWMB = self.tim2.channel(2, Timer.PWM, pin=Pin.cpu.A1) self.RH_BIN1 = Pin('PE10', pyb.Pin.OUT_PP) self.RH_BIN2 = Pin('PE11', pyb.Pin.OUT_PP) # LH Motor self.LH_STBY = Pin('PE7', pyb.Pin.OUT_PP) self.LH_PWMA = self.tim2.channel(3, Timer.PWM, pin=Pin.cpu.A2) self.LH_AIN1 = Pin('PE12', pyb.Pin.OUT_PP) self.LH_AIN2 = Pin('PE13', pyb.Pin.OUT_PP) self.LH_PWMB = self.tim2.channel(4, Timer.PWM, pin=Pin.cpu.A3) self.LH_BIN1 = Pin('PE14', pyb.Pin.OUT_PP) self.LH_BIN2 = Pin('PE15', pyb.Pin.OUT_PP) # Switch lights off self.LH.low() self.RH.low() self.TL.pulse_width_percent(0) self.HL.low() # Switch motor drivers off and PWM to low self.RH_PWMA.pulse_width_percent(self.power_R) self.RH_PWMB.pulse_width_percent(self.power_R) self.LH_PWMA.pulse_width_percent(self.power_L) self.LH_PWMB.pulse_width_percent(self.power_L) self.RH_STBY.low() self.LH_STBY.low() # Set all other motor pins low self.RH_AIN1.low() self.RH_AIN2.low() self.RH_BIN1.low() self.RH_BIN2.low() self.LH_AIN1.low() self.LH_AIN2.low() self.LH_BIN1.low() self.LH_BIN2.low() def Lights(self, status): if status == 1: self.HL.high() self.TL.pulse_width_percent(self.low_light) else: self.HL.low() self.TL.pulse_width_percent(0) def Brakes(self, status): if status == 1: self.TL.pulse_width_percent(100) 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 self.LH_PWMA.pulse_width_percent(percent_A) self.LH_PWMB.pulse_width_percent(percent_B) self.step_L += dir_L if self.step_L < 0: self.step_L = self.n_steps + dir_L if self.step_L >= self.n_steps: self.step_L = -1 + dir_L percent_A = self.power_R * math.sin(self.step_R * 2 * math.pi / self.n_steps) percent_B = self.power_R * math.cos(self.step_R * 2 * math.pi / self.n_steps) if percent_A > 0: self.RH_AIN1.high() self.RH_AIN2.low() else: self.RH_AIN1.low() self.RH_AIN2.high() percent_A *= -1 if percent_B > 0: self.RH_BIN1.high() self.RH_BIN2.low() else: self.RH_BIN1.low() self.RH_BIN2.high() percent_B *= -1 self.RH_PWMA.pulse_width_percent(percent_A) self.RH_PWMB.pulse_width_percent(percent_B) self.step_R += dir_R if self.step_R < 0: self.step_R = self.n_steps + dir_R if self.step_R >= self.n_steps: self.step_R = -1 + dir_R def MoveStep(self, n): if self.sspeed_L < 0: ldir = -n else: ldir = n self.speed_L += (self.sspeed_L * ldir) if self.speed_L > 255: self.dir_L = ldir self.dist_L += ldir self.speed_L -= 256 * n else: self.dir_L = 0 if self.sspeed_R < 0: rdir = -n else: rdir = n self.speed_R += (self.sspeed_R * rdir) if self.speed_R > 255: self.dir_R = rdir self.dist_R += rdir self.speed_R -= 256 * n else: self.dir_R = 0 self.DoStep(self.dir_L, self.dir_R) def SetPower(self, left, right): self.power_R = right self.power_L = left self.DoStep(0,0) def GetDist(self): return (self.dist_L, self.dist_R) def SetDist(self, dl, dr): self.dist_L = dl self.dist_R = dr def SetTarget(self, t_L, t_R): self.target_L = t_L self.target_R = t_R def GetTarget(self): return(self.target_L, self.target_R) def SetMaxSpeed(self, s_L, s_R): self.max_speed_L = s_L self.max_speed_R = s_R def Stop(self): self.dts_L = (self.acc * (self.sspeed_L // self.acc) ** 2) // 512 self.dts_R = (self.acc * (self.sspeed_R // self.acc) ** 2) // 512 if self.sspeed_L < 0: self.dts_L *= -1 if self.sspeed_R < 0: self.dts_R *= -1 self.target_L = self.dist_L + self.dts_L self.target_R = self.dist_R + self.dts_R def Motion(self, n): self.dts_L = (self.acc * (self.sspeed_L // self.acc) ** 2) // 512 self.dts_R = (self.acc * (self.sspeed_R // self.acc) ** 2) // 512 if self.sspeed_L < 0: self.dts_L *= -1 if self.sspeed_R < 0: self.dts_R *= -1 if self.target_L > (self.dist_L + self.dts_L) and self.sspeed_L < self.max_speed_L: self.sspeed_L += self.acc elif self.target_L < (self.dist_L + self.dts_L) and self.sspeed_L > -self.max_speed_L: self.sspeed_L -= self.acc elif self.target_L == self.dist_L and abs(self.sspeed_L) < 50: self.sspeed_L = 0 if self.target_R > (self.dist_R + self.dts_R) and self.sspeed_R < self.max_speed_R: self.sspeed_R += self.acc elif self.target_R < (self.dist_R + self.dts_R) and self.sspeed_R > -self.max_speed_R: self.sspeed_R -= self.acc elif self.target_R == self.dist_R and abs(self.sspeed_R) < 50: self.sspeed_R = 0 self.MoveStep(n) def FWD(self, dist): dl = int(self.dist_L + dist * 3.5866) dr = int(self.dist_R + dist * 3.5866) self.SetTarget(dl, dr) self.move = 1 self.step = 0 while (self.move == 1): if self.step > 0: self.Motion(self.step) self.step = 0 if self.dist_L == dl and self.dist_R == dr: self.move = 0 def TRN(self, r, alpha): dl = self.dist_L + int((r + 40.75) * 2 * math.pi * alpha / 360 * 3.5866) dr = self.dist_R + int((r - 40.75) * 2 * math.pi * alpha / 360 * 3.5866) self.SetTarget(dl, dr) self.move = 1 self.step = 0 while (self.move == 1): if self.step > 0: self.Motion(self.step) self.step = 0 if self.dist_L == dl and self.dist_R == dr: self.move = 0
class Controller: def __init__(self, uart, pwm_freq): self.uart = uart self.i_state = array('i', [0] * len(INAMES)) self.f_state = array('f', [0] * len(FNAMES)) # controller timer self.controller_timer = Timer(1) # motor power control self.nstby = Pin('NSTBY', mode=Pin.OUT_PP) self.nstby.value(0) # motors motor_pwm_timer = Timer(8, freq=pwm_freq) self.motor1 = TB6612( motor_pwm_timer.channel(3, Timer.PWM_INVERTED, pin=Pin('PWM_A')), Pin('AIN1', mode=Pin.OUT_PP), Pin('AIN2', mode=Pin.OUT_PP)) self.motor2 = TB6612( motor_pwm_timer.channel(1, Timer.PWM_INVERTED, pin=Pin('PWM_B')), Pin('BIN1', mode=Pin.OUT_PP), Pin('BIN2', mode=Pin.OUT_PP)) # encoders self.enc1 = init_encoder(4, 'ENC_A1', 'ENC_A2', Pin.AF2_TIM4) self.enc2 = init_encoder(3, 'ENC_B1', 'ENC_B2', Pin.AF2_TIM3) # gyro i2c = I2C(1, freq=400_000) imu = BNO055(i2c, crystal=True, transpose=(2, 0, 1), sign=(0, 0, 1)) imu.mode(NDOF_FMC_OFF_MODE) sleep_ms(800) imu.iget(QUAT_DATA) self.imu = imu # pid controllers self.pid = [ PID(1, 7, 50, 0, -100, 100), PID(1, 7, 50, 0, -100, 100), ] def start(self, fs, controller_name="duty_control"): self.stop() self.control_laws = getattr(self, controller_name) self.set_fs(fs) self.nstby.value(1) gc.collect() self.controller_timer.init(freq=fs, callback=self.control) def stop(self): self.controller_timer.callback(None) self.nstby.value(0) def shutdown(self): self.controller_timer.deinit() self.nstby.value(0) def set_fs(self, fs): for pid in self.pid: pid.Ts = 1 / fs def set_kp(self, pid_index, kp): self.pid[pid_index].kp = kp def set_ki(self, pid_index, ki): self.pid[pid_index].ki = ki def set_kd(self, pid_index, kd): self.pid[pid_index].kd = kd def control(self, timer): start_us = ticks_us() # locals i_state = self.i_state f_state = self.f_state # time index i_state[_ISTATE_K] += 1 # encoders enc1 = self.enc1 enc2 = self.enc2 cps1 = -c2(enc1.counter()) enc1.counter(0) cps2 = c2(enc2.counter()) enc2.counter(0) i_state[_ISTATE_ENC1] += cps1 i_state[_ISTATE_ENC2] += cps2 f_state[_FSTATE_CPT1] = cps1 f_state[_FSTATE_CPT2] = cps2 # gyro imu = self.imu imu.iget(QUAT_DATA) f_state[_FSTATE_QUAT_W] = w = imu.w / (1 << 14) f_state[_FSTATE_QUAT_X] = x = imu.x / (1 << 14) f_state[_FSTATE_QUAT_Y] = y = imu.y / (1 << 14) f_state[_FSTATE_QUAT_Z] = z = imu.z / (1 << 14) sinp = 2 * (w * y - z * x) if abs(sinp) >= 1: # use 90 degrees if out of range pitch = math.copysign(math.pi / 2, sinp) else: pitch = math.asin(sinp) pitch *= RAD2DEG f_state[_FSTATE_PITCH] = pitch # call control code self.control_laws() # controller execution time i_state[_ISTATE_DT1] = ticks_diff(ticks_us(), start_us) # status uart = self.uart uart.writechar(CMD_STATE) uart.write(i_state) uart.write(f_state) # total execution time i_state[_ISTATE_DT2] = ticks_diff(ticks_us(), start_us) def duty_control(self): f_state = self.f_state self.motor1.speed(f_state[_FSTATE_DUTY1]) self.motor2.speed(f_state[_FSTATE_DUTY2]) def speed_control(self): f_state = self.f_state pid = self.pid cps1 = f_state[_FSTATE_CPT1] cps2 = f_state[_FSTATE_CPT2] # control pid[PID_CPT1].setpoint = f_state[_FSTATE_CPT1_SP] pid[PID_CPT2].setpoint = f_state[_FSTATE_CPT2_SP] duty1 = pid[PID_CPT1].update(cps1) duty2 = pid[PID_CPT2].update(cps2) self.motor1.speed(duty1) self.motor2.speed(duty2) f_state[_FSTATE_DUTY1] = duty1 f_state[_FSTATE_DUTY2] = duty2
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() if 0 <= count <= self.HYSTERESIS: # overflow self._ticks = self._ticks + (timer.period() - self._lastRead + count) self._lastRead = count elif (timer.period() - self.HYSTERESIS) <= count <= timer.period(): # underflow self._ticks = self._ticks - (self._lastRead + timer.period() - count) self._lastRead = count else: # hysteresis not big enough #LED(1).on() # turn on inbuilt red led to show error pass
#--------------定时器部分 START ------------------- is_need_send_data = False # 是否需要发送数据的信号标志 def uart_time_trigger(timer): ''' 串口发送数据的定时器,定时器的回调函数 ''' global is_need_send_data is_need_send_data = True # 初始化定时器 频率为20HZ 每秒执行20次 tim = Timer(4, freq=20) # 设定定时器的回调函数 tim.callback(uart_time_trigger) #--------------定时器部分 END ------------------- #--------------直线与直角检测部分 START ------------------- # 直线灰度图颜色阈值 LINE_COLOR_THRESHOLD = [(0, 60)] # 如果直线是白色的,阈值修改为: # LINE_COLOR_THRESHOLD = [(128, 255)] # 取样窗口
green_led = pyb.LED(2) def turn_green_led_on(timer): green_led.on() def turn_green_led_off(timer): green_led.off() green_led_timer = Timer( 4, freq=200) # create a timer object using timer 4 - trigger at 1Hz green_led_timer.callback( turn_green_led_on) # set the callback to our tick function green_led_timer_channel = green_led_timer.channel(1, Timer.PWM, callback=turn_green_led_off, pulse_width_percent=50) #green_led_on = False #magnitude = 0 #def tick(timer): # we will receive the timer object when being called #global green_led_on ##if magnitude > 20: ##green_led_on = True ##else: ##green_led_on = False #pyb.LED(2).toggle()
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)
from machine import I2C import HTS221 from pyb import Timer i2c = I2C(1) hts = HTS221.HTS221(i2c) def tim_irq(t): print(hts.get_irq()) tim = Timer(1, freq=1) tim.callback(tim_irq)
from pyb import Pin, Timer p = Pin('PA0') acu_pulso = 0 def tick(timer): global acu_pulso acu_pulso += 1 tim = Timer(2, freq=400) ch = tim.channel(1, Timer.PWM, pin=p) ch.pulse_width_percent(50) tim.callback(tick)
g_find_place_circle=0 g_find_flag=0 g_cnt=0 #摄像头传感器设置 sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.QQQVGA) #QQQVG:80*60 sensor.skip_frames(time=2000) #略过前两秒的数据 sensor.set_auto_gain(False) sensor.set_auto_whitebal(False) #串口设置 uart=UART(3,115200) uart.init(115200,bits=8,parity=None,stop=1) #时钟设置 timer=Timer(4,freq=20) timer.callback(over_time) led2=LED(2) led2.on() led3=LED(3) Key1=Pin('P0',Pin.IN,Pin.PULL_UP) Key2=Pin('P1',Pin.IN,Pin.PULL_UP) clock=time.clock() while True: #修正镜头畸变 img=sensor.snapshot().lens_corr(1.8) c=img.find_circles(threshold=3500,x_margin=10,y_margin=10,r_margin=10) find_circle=False if c: find_circle=True if g_mode==0:
from pyb import Timer import micropython #Import light intensity needed module import LightIntensity import time micropython.alloc_emergency_exception_buf(100) print('pin init') Pin('Y11', Pin.OUT_PP).low() #GND Pin('Y9', Pin.OUT_PP).high() #VCC #LED shining regularly(using timer) to indicate the program is running correctly tim1 = Timer(1, freq=1) tim1.callback(lambda t: pyb.LED(1).toggle()) if __name__ == '__main__': while True: print('Smart IoT Plant System-Device') print(LightIntensity.readLight()) time.sleep(2) #send on-line message to gateway to notifiy and obtain own data from gateway's database ###reference begin### """ import pyb from pyb import Pin from ds18x20 import DS18X20 from pyb import Timer
return cb4 # create a timer with a callback, using callback(None) to stop tim = Timer(1, freq=100, callback=cb1) pyb.delay(5) print("before cb1") pyb.delay(15) # create a timer with a callback, using deinit to stop tim = Timer(2, freq=100, callback=cb2) pyb.delay(5) print("before cb2") pyb.delay(15) # create a timer, then set the freq, then set the callback tim = Timer(4) tim.init(freq=100) tim.callback(cb1) pyb.delay(5) print("before cb1") pyb.delay(15) # test callback with a closure tim.init(freq=100) tim.callback(cb3(3)) pyb.delay(5) print("before cb4") pyb.delay(15)
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()