def _process_rotary_pins(self, pin): old_value = self._value clk_dt_pins = ( self._hal_get_clk_value() << 1) | self._hal_get_dt_value() # Determine next state if self._half_step: self._state = _transition_table_half_step[ self._state & _STATE_MASK][clk_dt_pins] else: self._state = _transition_table[self._state & _STATE_MASK][clk_dt_pins] direction = self._state & _DIR_MASK incr = 0 if direction == _DIR_CW: incr = 1 elif direction == _DIR_CCW: incr = -1 incr *= self._reverse if self._range_mode == self.RANGE_WRAP: self._value = _wrap(self._value, incr, self._min_val, self._max_val) elif self._range_mode == self.RANGE_BOUNDED: self._value = _bound(self._value, incr, self._min_val, self._max_val) else: self._value = self._value + incr try: if old_value != self._value and len(self._listener) != 0: micropython.schedule(_trigger, self) except: pass
def _echoRead(self, pin, index): if pin.value(): self.echos[index]['start'] = time.ticks_us() elif self.echos[index]['end'] == 0: self.timer.deinit() self.echos[index]['end'] = time.ticks_us() micropython.schedule(self._measureNextRef, 0)
def thread(): while True: try: micropython.schedule(task, None) except RuntimeError: # Queue full, back off. utime.sleep_ms(10)
def on_espnow_message(self, message): self.log("<-on_espnow_message: scheduling callback") if not self.msg_callback: self.log("<-on_espnow_message: no callback") return micropython.schedule(self.msg_callback, message) self.log("<-on_espnow_message: callback scheduled")
async def main(): flag = asyncio.ThreadSafeFlag() # Set the flag from within the loop. t = asyncio.create_task(task(1, flag)) print("yield") await asyncio.sleep(0) print("set event") flag.set() print("yield") await asyncio.sleep(0) print("wait task") await t # Set the flag from scheduler context. print("----") t = asyncio.create_task(task(2, flag)) print("yield") await asyncio.sleep(0) print("set event") micropython.schedule(set_from_schedule, flag) print("yield") await asyncio.sleep(0) print("wait task") await t # Flag already set. print("----") print("set event") flag.set() t = asyncio.create_task(task(3, flag)) print("yield") await asyncio.sleep(0) print("wait task") await t
def sample_callback(self, *args, **kwargs): from lib.utils import update_buffer self.periph_manager.adc_read_to_buff(size=1) self.sample_counter += 1 # this will only be true every 1s once buffer fills if self.sample_counter >= self.buffer_size: self.periph_manager.write_led("red", 1) data = self._read_internal_buffer( preprocess=self.preprocessing_enabled) update_buffer(self.output_buffer, list(data), self.buffer_size, inplace=True) self.sample_counter = 0 self.periph_manager.write_led("red", 0) # TODO: workout how to run decoding in another handler as # this could take a non-negligible amount of time which # would disrupt consistency of sampling freq. For now, # we can schedule this function to run 'soon' while allowing other # ISRs to interrupt it if need be. try: schedule(self.decode, None) except RuntimeError: # if schedule queue is full, run now self.decode()
def timer_cb(self, t): lv.tick_inc(self.delay) # Passing self.task_handler would cause allocation. try: micropython.schedule(self.task_handler_ref, 0) except RuntimeError: pass
def debug_output(self, timer): def do_debug(arg): debug_string = "\n" for channel in self.channels: voltage_and_current = channel.voltage_and_current v = voltage_and_current["voltage"] c = voltage_and_current["current"] t = channel.temperature debug_string += "{} | Capacity: {}mAh | Current: {}mA | Voltage: {}v | Temp: {}C | State: {} \n".format( channel.channel, round(channel.discharge_stats.get_milliamp_hours(), 1) if channel.discharge_stats else 0, c, v, t, channel.state, ) gc.collect() # print(chr(27) + "[2J") log.debug(debug_string) log.debug("FREE RAM: " + str(gc.mem_free())) log.debug("Up Time: " + str(time.time())) micropython.schedule(do_debug, None)
def button_hdlr(_pin): global last_press state = machine.disable_irq() if utime.time() - last_press > 1: last_press = utime.time() micropython.schedule(debounce_press, 0) machine.enable_irq(state)
def schedule_in(handler, delay_ms): def _wrap(_arg): handler() if _timer: _timer.init(mode=machine.Timer.ONE_SHOT, period=delay_ms, callback=_wrap) else: micropython.schedule(_wrap, None)
def activate_task(self, id): if id not in self.task_list: print('Error: no task with id: ', id) else: if self.verbose > 1: print('Activate task ', id) self.task_list[id].switch_to_ready() micropython.schedule(self.schedule_task, None)
def select(t): global sel_i, run, btn_sel if not btn_sel.value() and not run: print("sel button") sel_i = (sel_i + 1) % 4 micropython.schedule(update_display, 0) btn_sel.irq(handler=sel_debounce)
def interrupt_callback(self, line=None): self.interrupt_time = utime.ticks_ms() if self._calling_callback: return if self._interrupt: self._interrupt.disable() self._calling_callback = True micropython.schedule(self._allocation_scheduled_callback, line)
def pulse_isr(state): """ Interrupt service routine for input pin state change. Schedule the decrement outside of the ISR. """ print("Pulse ISR triggred", end=" ") schedule(power_meter.count, 1)
def publish(self, name, *args, **kwargs) -> None: if name not in self._subscribers: return arg = (name, args, kwargs) for subscriber in self._subscribers[name]: schedule(subscriber, arg)
def schedule(tim): """ A simple call back function that just schedules publish_data function :param: None :return: None """ micropython.schedule(publish_data, 0)
def switch_detect(self,pin): if self.last_button_status == self.sw_pin.value(): return self.last_button_status = self.sw_pin.value() if self.sw_pin.value(): micropython.schedule(self.call_handlers, Rotary.SW_RELEASE) else: micropython.schedule(self.call_handlers, Rotary.SW_PRESS)
def _debounce(self, _): if self.pin.value() == self._value: if self._value == self._release_value: callback = self._on_release_callback else: callback = self._on_press_callback schedule(callback, None) self._register_irq()
def callback_outer(arg): global done micropython.schedule(callback_inner, 0) # need a loop so that the VM can check for pending events for i in range(2): pass print('outer') done += 1
def callback(arg): global done try: for i in range(100): micropython.schedule(lambda x: x, None) except RuntimeError: print('RuntimeError') done = True
def callback(arg): global done try: for i in range(100): micropython.schedule(lambda x:x, None) except RuntimeError: print('RuntimeError') done = True
def do_output(self, t): if self.wch: self.wbuf[self.widx] = self.wch self.widx += 1 if self.wch == ord('\n'): self.wprint_len = self.widx # Save for schedule micropython.schedule(printbuf, self) self.widx = 0 self.wch = b''
def cb(bus, reason): global ary try: bus.recv(0, ary) except Exception as e: print('Exception', e) micropython.schedule(cb_sched, None)
def i_cb(self, pinObj): ts1 = time.ticks_ms() if time.ticks_diff(ts1, self.ts)< 100: # toss away keybounce spikes return self.ts = ts1 try: schedule(self.i2_cb, None) # sched has small stack (4 !) and seems fragile anyway except: pass
def timer_cb(self, t): # Can be called in Interrupt context # Use task_handler_ref since passing self.task_handler would cause allocation. lv.tick_inc(self.delay) if self.scheduled < self.max_scheduled: try: micropython.schedule(self.task_handler_ref, 0) self.scheduled += 1 except: pass
def cl_callback(self, pin): self.rotary_history = \ ((self.rotary_history & 0b11) << 2) \ + (0b10 if pin.value() == 1 else 0) \ + (0b01 if self.current_data else 0) if self.rotary_history == turn_cw: schedule(self.on_down, 0) elif self.rotary_history == turn_ccw: schedule(self.on_up, 0)
def __repr__(self): # See: micropython.alloc_emergency_exception_buf(100) objState.strState = STATE_RUNNING objState.listErrorMessages = [] timer1.init(freq=0.5) # 0.5 Hz timer1.callback( lambda objTimer: micropython.schedule(schedule_timer1, 4712)) button1.callback(lambda: micropython.schedule(schedule_button, 4712)) return ''
def _fillbuf(self,tim): asm_tools.s_conv(self._outHTop1 if self._phase else self._outHBuf1, self._outHTop2 if self._phase else self._outHBuf2, self._outFBuf,self._outFShift,self._buffArgs1,self._buffArgs2) self._phase ^= 1 if self.ready: self.ready = False micropython.schedule(_mix_fillbuf,None) else: self.underrun += 1
def rotary_change(self, pin): new_status = (self.dt_pin.value() << 1) | self.clk_pin.value() if (new_status == self.last_status): return transition = (self.last_status << 2) | new_status if transition == 0b1110: micropython.schedule(self.call_handlers, Rotary.ROT_CW) elif transition == 0b1101: micropython.schedule(self.call_handlers, Rotary.ROT_CCW) self.last_status = new_status
def exec_lm_pipe_schedule(taskstr): """ Wrapper for exec_lm_pipe - fix IRQ execution limit - magic """ try: schedule(exec_lm_pipe, taskstr) return True except Exception as e: errlog_add("exec_lm_pipe_schedule error: {}".format(e)) return False
def handle_reset(self, p): machine.disable_irq() import micropython import time if p.value() == 0: time.sleep_ms(500) if p.value() == 0: print("Resetting Device...") micropython.schedule(self.hard_reset_ref, 0)
def cb(p): global icnt icnt += 1 print('cb', p, x11()) micropython.schedule(iclear, 1)
def cbg(p): global icnt icnt += 1 micropython.schedule(igclear, 1)
try: micropython.schedule except AttributeError: print('SKIP') raise SystemExit # Basic test of scheduling a function. def callback(arg): global done print(arg) done = True done = False micropython.schedule(callback, 1) while not done: pass # Test that callbacks can be scheduled from within a callback, but # that they don't execute until the outer callback is finished. def callback_inner(arg): global done print('inner') done += 1 def callback_outer(arg): global done micropython.schedule(callback_inner, 0) # need a loop so that the VM can check for pending events