async def _step(self, direction, delay=None): delay = delay or self.TIMER_DELAY _speed = 1000 * direction cur_pos = self._stepper.count self._stepper.set_speed(_speed) uasyncio.sleep_ms(1000) self._stepper.set_speed(_speed * -1)
async def step_a(): pins = [] st_a = ["D1", "D2", "D3", "D4"] for i in range(0, 4): pins.append(Pin(PIN_MAP[st_a[i]], Pin.OUT)) await angular_step(angle=360, direction=2, waiting_time=2, pins=pins) asyncio.sleep_ms(1000) await angular_step(angle=360, direction=-2, waiting_time=2, pins=pins)
async def step_b(): pins = [] st_b = ["D5", "D6", "D7", "D8"] for i in range(0, 4): pins.append(Pin(PIN_MAP[st_b[i]], Pin.OUT)) await angular_step(angle=360, direction=-2, waiting_time=2, pins=pins) asyncio.sleep_ms(1000) await angular_step(angle=360, direction=2, waiting_time=2, pins=pins)
async def calibrate_motor(self): self.log.info("starting motor calibration") self._status = self.CALIBRATING self._calibrating = True while self._calibrating: self._motor.move_at_speed(150) self.check_hall() uasyncio.sleep_ms(1) self._motor.stop() self._status = self.READY
def do_calibrate(t_channel, np): cycles = 48 cul = 0 for i in range(cycles): cul += t_channel.read() if i < LEDS: np[i] = BLUE np.write() uasyncio.sleep_ms(segment_wait) uasyncio.sleep_ms(800) # just so wee can see all the LEDs lit up return int(cul / cycles)
async def drain_queue(self, sleep_ms=50): while True: try: self.active_queue.popleft() except (ValueError, IndexError): print('draining complete') break except Exception: print('other error while draining') break asyncio.sleep_ms(sleep_ms)
async def readPulse(self,tms): print("Reading a trace") if self.pulse_T < 1: delay = int(self.pulse_T*1000) for i in range(500): self.trace[i] = self.adc.read() >> 4 asyncio.sleep_us(delay) else: for i in range(500): self.trace[i] = self.adc.read() >> 4 asyncio.sleep_ms(int(self.pulse_T))
def luminance(self, mode): # continuous modes if mode & 0x10 and mode != self.mode: self.set_mode(mode) # one shot modes if mode & 0x20: self.set_mode(mode) # earlier measurements return previous reading uasyncio.sleep_ms(24 if mode in (0x13, 0x23) else 180) data = self.bus.readfrom(self.addr, 2) factor = 2.0 if mode in (0x11, 0x21) else 1.0 return (data[0] << 8 | data[1]) / (1.2 * factor)
async def instructions(server_ip, server_port, path): global ROUTINE global ROUTINE_COMPLETE global LAST_COMMAND global ROUTINE_LENGTH routine = [] url = "http://" + server_ip + ":" + str(server_port) + path pb_headers = {'Content-Type': 'application/json'} while not ROUTINE_COMPLETE: while ROUTINE_LENGTH >= MAX_QUEUE - 1: await asyncio.sleep_ms(0) number_of_commands = MAX_QUEUE - ROUTINE_LENGTH data = ujson.dumps({ 'ip': IPADDRESS, 'limit': number_of_commands, 'last_command': str(LAST_COMMAND) }) retry_max = 5 i = 0 gc.collect() while len(routine) == 0: try: response = urequests.post(url, headers=pb_headers, json=data) if i > 0: asyncio.sleep_ms(i * 100) routine_json = response.json() response.close() routine = list(sorted(routine_json.items())) except Exception as e: print("Failed to retrieve commands: {}".format(e)) pass if i >= retry_max + 1: print("Max Retry reached") ROUTINE_COMPLETE = True break i = i + 1 if len(routine) == 1: if routine[0][0] is 'end': ROUTINE_COMPLETE = True if ROUTINE_COMPLETE: print("Last Command Received") await asyncio.sleep_ms(0) else: if len(routine) > 0: LAST_COMMAND = int(routine[-1][0]) ROUTINE.extend(routine) routine = [] ROUTINE_LENGTH = len(ROUTINE) await asyncio.sleep_ms(0)
async def rechts_gedrukt(): while True: # rechts gedrukt ? if knop_rechts.value() == 0: # teller vermeerderen gvars.teller += 2 if gvars.teller > 1024: gvars.teller = 1024 # toon teller print('Teller=%d' % (gvars.teller)) # debounce while knop_rechts.value() == 0: asyncio.sleep_ms(gvars.debounce_time) # even wachten await asyncio.sleep_ms(gvars.debounce_time)
async def links_gedrukt(): while True: # links gedrukt ? if knop_links.value() == 0: # teller verminderen gvars.teller -= 2 if gvars.teller < 0: gvars.teller = 0 # toon teller print('Teller=%d' % (gvars.teller)) # debounce while knop_links.value() == 0: asyncio.sleep_ms(gvars.debounce_time) # even wachten await asyncio.sleep_ms(gvars.debounce_time)
def sensor_values(self): ''' 同步模式获取值 ''' from utime import sleep_ms if self.__prepare != None: self.__prepare() sleep_ms(self.__delay) l = [] for s in self.__sensors: l.append(s.value) v = {} v['d'] = self.__name v['s'] = l return v
def connect(ssid, auth, timeout=16000): from network import WLAN, STA_IF, AP_IF global uplink uplink = WLAN(STA_IF) uplink.active(True) uplink.connect(ssid, auth) started = ticks_ms() while True: if uplink.isconnected(): return True else: if ticks_diff(ticks_ms(), started) < timeout: sleep_ms(100) continue else: return False
def __await__(self): if upython: while not self(): yield from asyncio.sleep_ms(self._tim_short_ms) else: # CPython: Meet requirement for generator in __await__ # https://github.com/python/asyncio/issues/451 yield from self._status_coro().__await__()
def __callback(self, b): log.debug("IRQ data: %r", b) state = disable_irq() tm = ticks_ms() log.debug("tm: %d, old: %d, %gap", tm, self.ticks, self.cool_down_gap) if tm > self.ticks + self.cool_down_gap: self.ticks = tm try: self._get_data(b) if self.handler is not None: log.debug("Call handler") schedule(self.handler, self.__handler_data) if self.queue is not None: log.debug("Send sensor data to queue") create_task(self.queue.put(self.__handler_data)) sleep_ms(self.interval) except BaseException as e: # NOSONAR log.error("Excetion while check and call irq handler: %r", e) enable_irq(state)
async def toggle_LED(): from machine import Pin # instances voor led en drukknop led = Pin(myGlobals.LED, Pin.OUT) knop = Pin(myGlobals.KNOP, Pin.IN, Pin.PULL_UP) # led initialsatie led.value(myGlobals.LEDState) # oneindige lus while True: # knop gedrukt ? if knop.value() == 0: # debounce while knop.value() == 0: asyncio.sleep_ms(myGlobals.debounce_time) # toggle LED myGlobals.LEDState = not myGlobals.LEDState # update LED led.value(myGlobals.LEDState) # even wachten await asyncio.sleep_ms(myGlobals.debounce_time)
async def test(): #print('This test takes 10s to complete.') while True: commands = ['AT', 'AT', 'AT'] pick = random.randint(0, len(commands) - 1) #print(pick) cmd = commands[pick] #print(cmd) #for cmd in ['Run', 'Poo',None]: print("Sending:\n" + cmd) res = await rockblock.send_command(cmd) # can use b''.join(res) if a single string is required. if res: print('Result is:') for line in res: print(line.decode('UTF8'), end='') print("----\n") else: print('Timed out waiting for result.') asyncio.sleep_ms(1000)
async def setIntensity(pin, mult, lock): # oneindige lus while True: # knop ingedrukt if not pin.value(): # debounce while not pin.value(): asyncio.sleep_ms(myGlobals.debounce_ms) # lock om te verhinderen dat andere routines deze globale variabele kunnen aanpassen await lock.acquire() # intensiteit bijwerken myGlobals.intensity += 50*mult if myGlobals.intensity < 0: myGlobals.intensity = 0 if myGlobals.intensity > 1023: myGlobals.intensity = 1023 # lock vrijgeven await asyncio.sleep_ms(myGlobals.debounce_ms) lock.release() # coroutine pauzeren await asyncio.sleep_ms(50)
async def light_loop(): global led, relay global name, light_changed time_cnt = 0 led.rgb_light() mqtt_client.subscribe(MQTT_COMMAND_TOPIC.encode()) while True: mqtt_client.check_msg() if light_changed: light_changed = False led.rgb_light() if time_cnt >= 20: mqtt_report(mqtt_client) time_cnt = 0 time_cnt = time_cnt + 1 uasyncio.sleep_ms(50)
async def run(self): while True: if self.status == self.PLAYING: if self.has_song_just_finished: _debug("next") mp3.next() if not self.is_card_still_there: self.pause() #sometimes pause gets ignored by the player, so lets pause again, can't harm. yield from asyncio.sleep_ms(100) self.pause() else: if not self.button.value(): #button pressed if time.time() - self.button_last_pressed >= 2: #mind. 2 Sekunde seit letztem mal mp3.next() self.button_last_pressed = time.time() elif self.status == self.PAUSED: #resume folder or play new one #also check special cards uid = self.card_id _debug("uid", uid) if uid == self.SPECIAL_CARDS["end_program"]: mp3.stop() raise SystemExit('Stop program') elif uid == self.SPECIAL_CARDS["next_unassigned_folder"]: self.play_folder(self.rfid_cards.next_card_index()) elif uid: folder_id = self.rfid_cards.card_index(uid) _debug("folder_id", folder_id) if folder_id == self.current_folder: _debug("same folder", folder_id) #user put same card back self.resume() else: # new card self.play_folder(folder_id) _debug("new card", folder_id) yield from asyncio.sleep_ms(100)
async def light_loop(): global led, relay, button global color, name, brightness, light_changed switch_status_last = 1 LED_status = 1 color = 2 # blue brightness = 100 # here 100% == 1 led.rgb_light(0, 0, 255, brightness/100.0) time_cnt = 0 # 订阅 mqtt_client.subscribe(MQTT_CONTROL_TOPIC.encode()) while True: # 检查服务器是否有待处理的消息。如果是,则以与wait_msg()相同的方式处理,如果不是,则立即返回。 mqtt_client.check_msg() switch_status = button.state() LED_status = relay.state() if switch_status != switch_status_last: if switch_status == 0 and switch_status_last == 1: LED_status = 0 if LED_status else 1 relay.set_state(LED_status) switch_status_last = switch_status if light_changed: light_changed = False led.rgb_light(255 if color == 0 else 0, 255 if color == 1 else 0, 255 if color == 2 else 0, brightness/100.0) if time_cnt >= 20: mqtt_report(mqtt_client, color, name, LED_status, brightness) time_cnt = 0 time_cnt = time_cnt+1 time.sleep_ms(50) uasyncio.sleep_ms(50)
def __await__(self): while not self._flag: yield from asyncio.sleep_ms(self.delay_ms)
async def async_blink_int(led_pin=2, count=1, on_time=500): for _ in range(count): pin_change(led_pin, False) asyncio.sleep_ms(on_time) pin_change(led_pin, True) asyncio.sleep_ms(on_time)
def __await__(self): while self._flag is not True: yield from asyncio.sleep_ms(self.__poll_ms)
async def step_a(): st_mot = Model_28BYJ_48(["D1", "D2", "D3", "D4"]) await st_mot.angular_step(angle=360, direction=2, waiting_time=2) asyncio.sleep_ms(100)
self.led = Pin(led_no) self.rate = 0 loop = asyncio.get_event_loop() loop.create_task(self.run()) async def run(self): while True: if self.rate <= 0: await asyncio.sleep_ms(200) else: self.led.value(not self.led.value()) await asyncio.sleep_ms(int(500 / self.rate)) def flash(self, rate): self.rate = rate def on(self): self.led.on() self.rate = 0 def off(self): self.led.off() self.rate = 0 if __name__ == '__main__': led = LED_async(16) led.on() asyncio.sleep_ms(1000) led.off()
import uasyncio as asyncio async def hello(): for _ in range(10): print('Hello world.') await asyncio.sleep(1) loop = asyncio.get_event_loop() hellofunc = hello() loop.create_task(hellofunc) loop.run_until_complete(asyncio.sleep_ms(15000)) # loop.run_until_complete(hellofunc)
async def step_b(): st_mot = Model_28BYJ_48(["D5", "D6", "D7", "D8"]) await st_mot.angular_step(angle=360, direction=-2, waiting_time=2) asyncio.sleep_ms(100)
def __iter__(self): # Await a connection while not self(): yield from asyncio.sleep_ms( self._tim_short) # V3 note: this syntax works.
def __iter__(self): # Await a connection while not self(): yield from asyncio.sleep_ms(self._tim_short)