def scroll(self, data, speed=120): DISPLAY_WIDTH = 16 # Display width in pixels. DISPLAY_HEIGHT = 8 # Display height in pixels. # Initialize LED matrix. matrix = Display(i2c) matrix.clear() # Initialize font renderer using a helper function to flip the Y axis # when rendering so the origin is in the upper left. def matrix_pixel(x, y): matrix._pixel(x, y, 1) with BitmapFont(DISPLAY_WIDTH, DISPLAY_HEIGHT, matrix_pixel) as bf: # Global state: pos = DISPLAY_WIDTH # X position of the message start. message_width = bf.width(data) # Message width in pixels. last = utime.ticks_ms() # Last frame millisecond tick time. speed_ms = 1200 / speed / 1000.0 # Scroll speed in pixels/ms. # Main loop: while True: # Compute the time delta in milliseconds since the last frame. current = utime.ticks_ms() delta_ms = utime.ticks_diff(current, last) last = current # Compute position using speed and time delta. pos -= speed_ms*delta_ms if pos < -message_width: pos = DISPLAY_WIDTH return # Clear the matrix and draw the text at the current position. matrix.fill(0) bf.text(data, int(pos), 0) # Update the matrix LEDs. matrix._show()
def main(): import utime, array # ESP stuff from machine import Pin, Signal import tphg, pm25 # Version 905 sensors - comment this line for stub.py #import stub # when no sensors are attached. import iot # IOT networking start_time = utime.ticks_ms() # let's track runtime (for measuring current usage) aq = {} id = machine.unique_id() chipId='{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}'.format(id[0], id[1], id[2], id[3], id[4], id[5]) # make each sensor its own group #aq.update(analog.measure()) #aq.update(dht11.measure()) #aq.update(enviro.measure()) #aq.update(ppd42.measure()) #aq.update(tph.measure()) aq.update(tphg.measure()) #aq.update(stub.measure()) # when you only want the MCU and no sensors. # for reasons I can't explain, UART takes time to setup - so do this last? WTF. aq.update(pm25.measure()) iot.init_ap(False) iot.init_sta(True) # Now let's post all iot.io_post(chipId,aq) #iot.io_post({"runtime": ((utime.ticks_ms() - start_time)/1000)}) print("Runtime is:", (utime.ticks_ms() - start_time)/1000) sleep.init(sleep_interval) # see you later!
def initiator_thread(chan): yield so = ['test', 0, 0] for x in range(4): # Test full duplex by sending 4 in succession so[1] = x chan.send(so) yield while True: while not chan.any(): # wait for response yield while chan.any(): # Deal with queue si = chan.get() print('initiator received', si) yield if si[1] == 3: # received last one break while True: yield 2 tim = utime.ticks_ms() chan.send(so) while not chan.any(): # wait for response yield so = chan.get() duration = utime.ticks_diff(tim, utime.ticks_ms()) print('initiator received', so, 'timing', duration)
def makegauge(self): ''' Generator refreshing the raw measurments. ''' delays = (5, 8, 14, 25) while True: self.i2c.writeto_mem(self.addr, 0xF4, b'\x2E') t_start = utime.ticks_ms() while utime.ticks_diff(t_start, utime.ticks_ms()) <= 5: yield None try: self.UT_raw = self.i2c.readfrom_mem(self.addr, 0xF6, 2) except: yield None self.i2c.writeto_mem(self.addr, 0xF4, str.encode(hex(0x34+(self.oversample_setting << 6)))) t_pressure_ready = delays[self.oversample_setting] t_start = utime.ticks_ms() while utime.ticks_diff(t_start, utime.ticks_ms()) <= t_pressure_ready: yield None try: self.MSB_raw = self.i2c.readfrom_mem(self.addr, 0xF6, 1) self.LSB_raw = self.i2c.readfrom_mem(self.addr, 0xF7, 1) self.XLSB_raw = self.i2c.readfrom_mem(self.addr, 0xF8, 1) except: yield None yield True
def send(self, buf, timeout=500): self.send_start(buf) start = utime.ticks_ms() result = None while result is None and utime.ticks_diff(utime.ticks_ms(), start) < timeout: result = self.send_done() # 1 == success, 2 == fail if result == 2: raise OSError("send failed")
def master(): csn = Pin(cfg['csn'], mode=Pin.OUT, value=1) ce = Pin(cfg['ce'], mode=Pin.OUT, value=0) if cfg['spi'] == -1: spi = SPI(-1, sck=Pin(cfg['sck']), mosi=Pin(cfg['mosi']), miso=Pin(cfg['miso'])) nrf = NRF24L01(spi, csn, ce, payload_size=8) else: nrf = NRF24L01(SPI(cfg['spi']), csn, ce, payload_size=8) nrf.open_tx_pipe(pipes[0]) nrf.open_rx_pipe(1, pipes[1]) nrf.start_listening() num_needed = 16 num_successes = 0 num_failures = 0 led_state = 0 print('NRF24L01 master mode, sending %d packets...' % num_needed) while num_successes < num_needed and num_failures < num_needed: # stop listening and send packet nrf.stop_listening() millis = utime.ticks_ms() led_state = max(1, (led_state << 1) & 0x0f) print('sending:', millis, led_state) try: nrf.send(struct.pack('ii', millis, led_state)) except OSError: pass # start listening again nrf.start_listening() # wait for response, with 250ms timeout start_time = utime.ticks_ms() timeout = False while not nrf.any() and not timeout: if utime.ticks_diff(utime.ticks_ms(), start_time) > 250: timeout = True if timeout: print('failed, response timed out') num_failures += 1 else: # recv packet got_millis, = struct.unpack('i', nrf.recv()) # print response and round-trip delay print('got response:', got_millis, '(delay', utime.ticks_diff(utime.ticks_ms(), got_millis), 'ms)') num_successes += 1 # delay then loop utime.sleep_ms(250) print('master finished sending; successes=%d, failures=%d' % (num_successes, num_failures))
def run(self): while True: iteration_start = utime.ticks_ms() self.perform_tasks() time_spent_on_tasks = utime.ticks_diff(utime.ticks_ms(), iteration_start) if time_spent_on_tasks < self.sleep_ms: utime.sleep_ms(utime.ticks_diff(self.sleep_ms, time_spent_on_tasks)) else: logger.warning('Skipping sleep - spent {}ms on tasks'.format(time_spent_on_tasks))
def Proc0(loops=LOOPS): global IntGlob global BoolGlob global Char1Glob global Char2Glob global Array1Glob global Array2Glob global PtrGlb global PtrGlbNext starttime = ticks_ms() for i in range(loops): pass nulltime = ticks_diff(ticks_ms(), starttime) PtrGlbNext = Record() PtrGlb = Record() PtrGlb.PtrComp = PtrGlbNext PtrGlb.Discr = Ident1 PtrGlb.EnumComp = Ident3 PtrGlb.IntComp = 40 PtrGlb.StringComp = "DHRYSTONE PROGRAM, SOME STRING" String1Loc = "DHRYSTONE PROGRAM, 1'ST STRING" Array2Glob[8 // 2][7 // 2] = 10 starttime = ticks_ms() for i in range(loops): Proc5() Proc4() IntLoc1 = 2 IntLoc2 = 3 String2Loc = "DHRYSTONE PROGRAM, 2'ND STRING" EnumLoc = Ident2 BoolGlob = not Func2(String1Loc, String2Loc) while IntLoc1 < IntLoc2: IntLoc3 = 5 * IntLoc1 - IntLoc2 IntLoc3 = Proc7(IntLoc1, IntLoc2) IntLoc1 = IntLoc1 + 1 Proc8(Array1Glob, Array2Glob, IntLoc1, IntLoc3) PtrGlb = Proc1(PtrGlb) CharIndex = 'A' while CharIndex <= Char2Glob: if EnumLoc == Func1(CharIndex, 'C'): EnumLoc = Proc6(Ident1) CharIndex = chr(ord(CharIndex)+1) IntLoc3 = IntLoc2 * IntLoc1 IntLoc2 = IntLoc3 // IntLoc1 IntLoc2 = 7 * (IntLoc3 - IntLoc2) - IntLoc1 IntLoc1 = Proc2(IntLoc1) benchtime = ticks_diff(ticks_ms(), starttime) - nulltime if benchtime == 0: loopsPerBenchtime = 0 else: loopsPerBenchtime = (loops * 1000 // benchtime) return benchtime, loopsPerBenchtime
def sub_cb(topic, msg): global t, maxt, mint dt = ticksdiff(t, ticks_ms()) print('echo received in {} ms'.format(dt)) print((topic, msg)) maxt = max(maxt, dt) mint = min(mint, dt)
def new_fix_time(self): """Updates a high resolution counter with current time when fix is updated. Currently only triggered from GGA, GSA and RMC sentences""" try: self.fix_time = utime.ticks_ms() except NameError: self.fix_time = time.time()
def main(quit=True): global t c = MQTTClient(CLIENT_ID, SERVER) # Subscribed messages will be delivered to this callback c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC, qos = QOS) print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC)) n = 0 pubs = 0 try: while 1: n += 1 if not n % 100: t = ticks_ms() c.publish(TOPIC, str(pubs).encode('UTF8'), retain = False, qos = QOS) c.wait_msg() pubs += 1 if not pubs % 100: print('echo received in max {} ms min {} ms'. format(maxt, mint)) if quit: return sleep(0.05) c.check_msg() finally: c.disconnect()
def perform_tasks(self): for t in self.interval_tasks: now = utime.ticks_ms() if not t['last_called'] or \ utime.ticks_diff(now, t['last_called']) >= t['interval']: t['last_called'] = now t['callback']()
def _log(self, message, *args): """ Outputs a log message to stdout. """ print('[{:>10.3f}] {}'.format( utime.ticks_ms() / 1000, str(message).format(*args) ))
def poll_ms(self, timeout=-1): s = bytearray(self.evbuf) if timeout >= 0: deadline = utime.ticks_add(utime.ticks_ms(), timeout) while True: n = epoll_wait(self.epfd, s, 1, timeout) if not os.check_error(n): break if timeout >= 0: timeout = utime.ticks_diff(deadline, utime.ticks_ms()) if timeout < 0: n = 0 break res = [] if n > 0: vals = struct.unpack(epoll_event, s) res.append((vals[1], vals[0])) return res
def _gauge(self): now=utime.ticks_ms() if utime.ticks_diff(now,self._last_read_ts)>self._new_read_ms: self._last_read_ts=now r=self._t_os+(self._p_os<<3)+(1<<6) self._write(BMP280_REGISTER_CONTROL,r) utime.sleep_ms(100) d=self._read(BMP280_REGISTER_DATA,6) self._p_raw=(d[0]<<12)+(d[1]<<4)+(d[2]>>4) self._t_raw=(d[3]<<12)+(d[4]<<4)+(d[5]>>4) self._t_fine=0 self._t=0 self._p=0
def scroll(self,data,speed=120): DISPLAY_WIDTH=16 DISPLAY_HEIGHT=8 matrix=Display(i2c) matrix.clear() def matrix_pixel(x,y): matrix._pixel(x,y,1) with BitmapFont(DISPLAY_WIDTH,DISPLAY_HEIGHT,matrix_pixel)as bf: pos=DISPLAY_WIDTH message_width=bf.width(data) last=utime.ticks_ms() speed_ms=1200/speed/1000.0 while True: current=utime.ticks_ms() delta_ms=utime.ticks_diff(current,last) last=current pos-=speed_ms*delta_ms if pos<-message_width: pos=DISPLAY_WIDTH return matrix.fill(0) bf.text(data,int(pos),0) matrix._show()
def _gauge(self): # TODO limit new reads now = utime.ticks_ms() if utime.ticks_diff(now, self._last_read_ts) > self._new_read_ms: self._last_read_ts = now r = self._t_os + (self._p_os << 3) + (1 << 6) self._write(BMP280_REGISTER_CONTROL, r) utime.sleep_ms(100) # TODO calc sleep d = self._read(BMP280_REGISTER_DATA, 6) # read all data at once (as by spec) self._p_raw = (d[0] << 12) + (d[1] << 4) + (d[2] >> 4) self._t_raw = (d[3] << 12) + (d[4] << 4) + (d[5] >> 4) self._t_fine = 0 self._t = 0 self._p = 0
def time_since_fix(self): """Returns number of millisecond since the last sentence with a valid fix was parsed. Returns 0 if no fix has been found""" # Test if a Fix has been found if self.fix_time == 0: return -1 # Try calculating fix time using utime; if not running MicroPython # time.time() returns a floating point value in secs try: current = utime.ticks_diff(utime.ticks_ms(), self.fix_time) except NameError: current = (time.time() - self.fix_time) * 1000 # ms return current
def __init__(self, pin, callback, *args, **kwargs): self.pin = machine.Pin(pin) self.touchpin = machine.TouchPad(self.pin) self.callback = callback self.avg_count = 15 self.samplerate = 120 self.threshold = 0.95 self.debounce_ms = 300 self.sample_sleep_ms = int(1000/self.samplerate) self.readings = [] self.configure(kwargs) self.callback_triggered_last = utime.ticks_ms() # Initial calibration for i in range(self.avg_count): utime.sleep_ms(self.sample_sleep_ms) self.readings.append(self.touchpin.read())
def test_main(): """Test function for verifying basic functionality.""" print("Running test_main") lcd = GpioLcd(rs_pin=Pin(4), enable_pin=Pin(17), d4_pin=Pin(5), d5_pin=Pin(18), d6_pin=Pin(21), d7_pin=Pin(22), num_lines=2, num_columns=20) lcd.putstr("It Works!\nSecond Line\nThird Line\nFourth Line") sleep_ms(3000) lcd.clear() count = 0 while True: lcd.move_to(0, 0) lcd.putstr("%7d" % (ticks_ms() // 1000)) sleep_ms(1000) count += 1
def perform(self) : current_tick = utime.ticks_ms() if not self.initial_tick : self.initial_tick = current_tick else : x = utime.ticks_diff(current_tick, self.initial_tick) if x == 0 : pass elif 0 < x : rgb = self.get_color(x) if rgb != self.prev_rgb : if self.verbose : logging.info("Lamp: setting color to {} from x={}", rgb, x) self.fill_pixels(rgb) self.prev_rgb = rgb else : # wrap around; start over logging.info("Lamp: tick wrap") self.initial_tick = current_tick return True
def main(): threshold = 1000 * 60 * 6 #threshold = 1000 * 30 start = utime.ticks_ms() while True: now = utime.ticks_ms() seconds = now // 1000 if seconds % 2 == 0: display.show(Image.CLOCK3) else: display.show(Image.CLOCK9) beep1 = utime.ticks_ms() beep2 = beep1 + 200 while utime.ticks_diff(now, start) > threshold: buzz_start = now display.show(Image.HEART) # beep if utime.ticks_diff(utime.ticks_ms(), beep1) > 0: music.pitch(1760, 100, wait=False) beep1 = beep1 + 2000 # beep if utime.ticks_diff(utime.ticks_ms(), beep2) > 0: music.pitch(1760, 100, wait=False) beep2 = beep2 + 2000 # button if button_a.is_pressed(): action = utime.ticks_ms() spend = utime.ticks_diff(action, buzz_start) display.scroll(str(spend)) if spend < 3000: threshold = 1000 * 60 * 6 else: threshold = 1000 * 60 * 3 #if spend < 3000: threshold = 1000 * 30 #else: threshold = 1000 * 10 start = utime.ticks_ms() break sleep(1000)
def poll(self): value = self.touchpin.read() weighted_value = sum(self.readings[-2:] + [value]) / 3 mean = self.get_current_mean() thresh = mean * self.threshold ratio = weighted_value / mean #logger.debug( # '[{}] Mean: {:04.0f}, Threshold: {:04.0f}, This: {:04.0f}, This weighted: {:04.0f} / {:.0%}' # .format(utime.ticks_ms(), mean, thresh, value, weighted_value, ratio) #) logger.debug('{} {} {}'.format(mean, weighted_value, int(ratio*100))) if weighted_value < thresh: now = utime.ticks_ms() if (utime.ticks_diff(now, self.callback_triggered_last) < self.debounce_ms): logger.info('Debounced') # Make reading affect mean less - this allows for slow recalibration #value += (thresh - value)*0.9 else: self.callback() self.callback_triggered_last = now self.readings.pop(0) self.readings.append(weighted_value)
def time(self): return time.ticks_ms()
def schedule(self, deadline: int, value: Any) -> None: deadline = utime.ticks_add(utime.ticks_ms(), deadline) if self.task is not None: schedule(self.task, value, deadline) else: self.before_task.append((deadline, value))
if fogottJel is not None: # Ha megjött a jel, akkor mutassa a gyaloglás képét. # Ako je stigao signal onda treba prikazati sliku pešačenja. display.show(kepFutas) break else: # Különben a "?!" jelet mutassa. # Inače se prikazuje "?!" znak. display.show(kepKerdFelkialt) radio.off() # Elkezdi mérni az időt tíz másodpercig. # Počinje meriti vreme do dest sekundi. # mostan je sada mostan = int(utime.ticks_ms() / 1000) while True: if int(utime.ticks_ms() / 1000) > mostan + 10: break else: if accelerometer.was_gesture("3g"): # povećava se broj koraka lepes += 1 display.show(Image.HAPPY) sleep(1000) # Megvannak a lépések, amit mb2 összeszámolt tíz mp alatt. # mb2 -nek el kell küldenie mb1 számára e lépések számát! # Sada imamo broj koraka učinjenih za deset sekundi. # Sada treba mb2 to poslati za mb1!
oled.text('connection...', 0, 48) oled.show() utime.sleep(1) oled.show() utime.sleep(1) for i in range(30): if wlan_client.check(): break oled.text('.', i * 8, 56) oled.show() utime.sleep(1) url = "http://worldtimeapi.org/api/timezone/Europe/Lisbon" # set timer update_time = utime.ticks_ms() - web_query_delay # main loop while True: if not wlan_client.check(): wlan_client.start() if utime.ticks_ms() - update_time >= web_query_delay: error_net = False try: response = urequests.get(url) except: error_net = True if not error_net or response.status_code == 200: # query success
#IRQ activation p4.irq(handler=get_frame,trigger=Pin.IRQ_RISING) #SPI at 20 MHz , the max according to the Lepton documentation vspi=SPI(2,baudrate=20000000,polarity=1,phase=1,sck=Pin(18),mosi=Pin(23), miso=Pin(19)) cs=Pin(5,Pin.OUT) cs.value(1) utime.sleep_ms(186) if c==0: pw2.deinit() p2.value(1) deadline = utime.ticks_add(utime.ticks_ms(), TIMEOUT) #/CS asserted cs.value(0) while (utime.ticks_diff(deadline, utime.ticks_ms()) > 0): if irq_flag: #p1=utime.ticks_us() #get the segments through SPI vspi.readinto(buff_video) #delta_t=utime.ticks_diff(utime.ticks_us(),p1) # exception , ENOMEM bug if flag_ex: if utime.ticks_diff(utime.ticks_ms(),t1_ex)>50: flag_ex=False #do not send the first frames and do not send during 50 ms if an exception has been raised
def solid(config, np, pixel_count): colors = config['colors'] elapsed = utime.ticks_ms() // config['period_ms'] current = elapsed % len(colors) np.fill(colors[current]) np.write()
def period_reset_time(self): # Time from now, in seconds, until the period resets and the velocity # totals are reset if not self.period: return 0 end = self.current_period + (self.period * 60) return (utime.ticks_ms() // 1000) - end
else: hue = 360 if touch.touchstates[2]: if sat > 1: sat -= 1 else: sat = 255 elif touch.touchstates[3]: if sat < 254: sat += 1 else: sat = 0 #aim to update state once every 100 miliseconds. if utime.ticks_ms() % 1000 == 0: # remap values to 8 bit ints for transfer - not efficient or accurate... hue = trunc(remap(hue, 0, 360, 0, 255)) sat = trunc(remap(sat, 0, 255, 0, 255)) hsvtuple = (hue, sat) radio.send_bytes(bytes(hsvtuple)) try: hsvtuple = tuple(radio.receive_bytes()) hue = hsvtuple[0] sat = hsvtuple[1] except: pass finally:
scpi("SENS:DLOG:TRAC:X:UNIT VOLT") scpi("SENS:DLOG:TRAC:X:STEP " + str(uStep)) scpi("SENS:DLOG:TRAC:X:RANG:MAX " + str(uMax)) scpi('SENS:DLOG:TRAC:X:LABel "Uset"') scpi("SENS:DLOG:TRAC:Y1:UNIT AMPER") scpi("SENS:DLOG:TRAC:Y1:RANG:MAX " + str(I_SET)) scpi('SENS:DLOG:TRAC:Y1:LABel "Imon"') scpi('INIT:DLOG:TRACE "/Recordings/' + diodeName + '.dlog"') scpi("OUTP 1") scpi("DISP:WINDOW:DLOG") ch = 1 t = ticks_ms() i = 0 while True: uSet = i * uStep if uSet > uMax: break setU(ch, uSet) #scpi("VOLT " + str(uSet)) t = ticks_add(t, TIME_STEP_MS) sleep_ms(ticks_diff(t, ticks_ms())) iMon = getI(ch) #iMon = scpi("MEAS:CURR?")
def start(self): self.start_ms = utime.ticks_ms() self.status = True # active
</tr> </table> <br> CPM intervala zadnjih 30 s: %s <br><br> %s </body> </html> """ CONV_FACTOR = 0.044444 count = 0 rom_count = 0 event_occured = 0 last_time = ticks_ms() tim = Timer(-1) tim_cpm = Timer(-1) tim_save = Timer(-1) tim_uart = Timer(-1) cpm = 0 sv = 0.0 file_status = 0 uart = None report_mode = 0 lcd = None def long_to_bytes(a): """Converts 2 bytes integer to encoded string""" return ("%c%c" % ((a >> 8) & 0xFF, a & 0xFF))
def send_unicast_message_with_ack(self, address: int, message_bytes: bytes, timeout: float = 5.0) -> float: """Sends a unicast message of message_bytes to address. Maximum of 64 bytes. Waits for Ack from the remote node and returns the time of flight in seconds. """ # Checks on parameters if address < 0 or address > 255: print('Invalid address (0-255): ' + str(address)) return -1 if len(message_bytes) < 2 or len(message_bytes) > 64: print('Invalid length of message_bytes (2-64): ' + str(len(message_bytes))) return -1 # Absorb any incoming bytes into the receive buffers to process later self.poll_receiver() # Store the default timeout #default_read_timeout = self._serial_port.timeout # Write the command to the serial port cmd_string = '$M' + '{:03d}'.format(address) + '{:02d}'.format( len(message_bytes)) cmd_bytes = cmd_string.encode('utf-8') + message_bytes # Check that it has written all the bytes. Return error if not. if self._uart.write(cmd_bytes) != len(cmd_bytes): print('Error writing command') return -1 # Await the first response from the serial port # Expecting '$M12300\r\n' 9 bytes resp_string = '$M12300\r\n' resp_bytes = self._uart.read(9) # Check that it has received all the expected bytes. Return error if not. if not resp_bytes: print('Error receiving bytes. None received.') return -1 if len(resp_bytes) != len(resp_string): print('Error receiving number of bytes=' + str(len(resp_bytes)) + ' expected=' + str(len(resp_string))) return -1 # If the address is invalid then returns 'E\r\n' # Set the temporary read timeout for the propagation delay #self._serial_port.timeout = timeout start_ms = utime.ticks_ms() # Now await the range or TO after 4 seconds # Expecting '#R255T12345\r\n' or '#TO\r\n' 13 or 5 bytes resp_string = '#R255T12345\r\n' resp_bytes = self._uart.read(13) while not resp_bytes and (utime.ticks_diff(utime.ticks_ms(), start_ms) < (timeout * 1000)): resp_bytes = self._uart.read(13) # Check that it has received all the expected bytes. Return error if not. if not resp_bytes: print('Error receiving bytes. None received.') return -1 if len(resp_bytes) != len(resp_string): print('Error receiving number of bytes=' + str(len(resp_bytes)) + ' expected=' + str(len(resp_string))) # Set the default read timeout #self._serial_port.timeout = default_read_timeout return -1 resp_string = resp_bytes.decode('utf-8') time_string = resp_string[6:11] time_int = int(time_string) # Convert the time value to a float seconds. T = time_int * 31.25E-6. time = float(time_int) * 31.25E-6 # Set the default read timeout #self._serial_port.timeout = default_read_timeout return time
def send_ping(self, address: int, timeout: float = 5.0) -> float: """Sends a ping to the addressed node and returns the one way time of flight in seconds from this device to the node address provided. """ # Checks on parameters if address < 0 or address > 255: print('Invalid address (0-255): ' + str(address)) return -1 # Absorb any incoming bytes into the receive buffers to process later self.poll_receiver() # Store the default timeout #default_read_timeout = self._serial_port.timeout # Write the command to the serial port cmd_string = '$P' + '{:03d}'.format(address) cmd_bytes = cmd_string.encode('utf-8') # Check that it has written all the bytes. Return error if not. if self._uart.write(cmd_bytes) != len(cmd_bytes): print('Error writing command') return -1 # Await the first response from the serial port # Expecting '$P255\r\n' 7 bytes resp_string = '$P255\r\n' resp_bytes = self._uart.read(7) # Check that it has received all the expected bytes. Return error if not. if not resp_bytes: print('Error receiving bytes. None received.') return -1 if len(resp_bytes) != len(resp_string): print('Error receiving number of bytes=' + str(len(resp_bytes)) + ' expected=' + str(len(resp_string))) return -1 # Set the temporary read timeout for the propagation delay #self._serial_port.timeout = timeout start_ms = utime.ticks_ms() # Now await the range or TO after 4 seconds # Expecting '#R255T12345\r\n' or '#TO\r\n' 13 or 5 bytes resp_string = '#R255T12345\r\n' resp_bytes = self._uart.read(13) while not resp_bytes and (utime.ticks_diff(utime.ticks_ms(), start_ms) < (timeout * 1000)): resp_bytes = self._uart.read(13) # Check that it has received all the expected bytes. Return error if not. if not resp_bytes: print('Error receiving bytes. None received.') return -1 if len(resp_bytes) != len(resp_string): print('Error receiving number of bytes=' + str(len(resp_bytes)) + ' expected=' + str(len(resp_string))) # Set the default read timeout #self._serial_port.timeout = default_read_timeout return -1 resp_string = resp_bytes.decode('utf-8') time_string = resp_string[6:11] time_int = int(time_string) # Convert the time value to a float seconds. T = time_int * 31.25E-6. time = float(time_int) * 31.25E-6 # Set the default read timeout #self._serial_port.timeout = default_read_timeout return time
def msg_authenticate(req: Msg) -> Cmd: global _state global _lastreq from apps.common import storage if not storage.is_initialized(): log.warning(__name__, 'not initialized') return msg_error(req.cid, _SW_CONDITIONS_NOT_SATISFIED) # we need at least keyHandleLen if len(req.data) <= _REQ_CMD_AUTHENTICATE_KHLEN: log.warning(__name__, '_SW_WRONG_LENGTH req.data') return msg_error(req.cid, _SW_WRONG_LENGTH) # check keyHandleLen khlen = req.data[_REQ_CMD_AUTHENTICATE_KHLEN] if khlen != 64: log.warning(__name__, '_SW_WRONG_LENGTH khlen') return msg_error(req.cid, _SW_WRONG_LENGTH) auth = overlay_struct(req.data, req_cmd_authenticate(khlen)) # check the keyHandle and generate the signing key node = msg_authenticate_genkey(auth.appId, auth.keyHandle) if node is None: # specific error logged in msg_authenticate_genkey return msg_error(req.cid, _SW_WRONG_DATA) # if _AUTH_CHECK_ONLY is requested, return, because keyhandle has been checked already if req.p1 == _AUTH_CHECK_ONLY: log.info(__name__, '_AUTH_CHECK_ONLY') return msg_error(req.cid, _SW_CONDITIONS_NOT_SATISFIED) # from now on, only _AUTH_ENFORCE is supported if req.p1 != _AUTH_ENFORCE: log.info(__name__, '_AUTH_ENFORCE') return msg_error(req.cid, _SW_WRONG_DATA) # check equality with last request if _lastreq is None or _lastreq.__dict__ != req.__dict__: if _state is not None: _state.kill() _state = None _lastreq = req # wait for a button or continue if _state is not None and utime.ticks_ms() > _state.deadline_ms: _state.kill() _state = None if _state is None: _state = ConfirmState(_CONFIRM_AUTHENTICATE, auth.appId) _state.fork() if _state.confirmed is None: log.info(__name__, 'waiting for button') return msg_error(req.cid, _SW_CONDITIONS_NOT_SATISFIED) _state = None buf = msg_authenticate_sign(auth.chal, auth.appId, node.private_key()) return Cmd(req.cid, _CMD_MSG, buf)
pic_no = 0 accel_array_zero = (255, 255, 255) #IMU_Image w_size = 8 view_size = 120 imu_Image = image.Image() imu_Image = imu_Image.resize(w_size, w_size) image_data_array = [] task = kpu.load(0x00300000) max_index = 0 view_mode = 0 class_time = array.array('d', [0 for ii in range(10)]) oldTime = utime.ticks_ms() rot_theta = 0 #uart initial fm.register(35, fm.fpioa.UART2_TX, force=True) fm.register(34, fm.fpioa.UART2_RX, force=True) uart_Port = UART(UART.UART2, 115200, 8, 0, 0, timeout=1000, read_buf_len=4096) while (True): view_Image = image.Image() # IMU Data to Image accel_array, accel_array2 = read_imu() w = cnt % w_size h = int(cnt / w_size) imu_Image.set_pixel(w, h, accel_array)
def record_spend(self, rule, amt): # record they spend some amount in this period rule.spent_so_far += amt if not self.period_started: self.period_started = (utime.ticks_ms() // 1000) or 1
import utime try: utime.sleep_ms except AttributeError: print("SKIP") raise SystemExit utime.sleep_ms(1) utime.sleep_us(1) print(utime.ticks_diff(utime.ticks_ms(), utime.ticks_ms()) <= 1) print(utime.ticks_diff(utime.ticks_us(), utime.ticks_us()) <= 500)
def tick(self): # Detect the input information buttonLevel = self._pin.value() now = ticks_ms() # Implementation of the state machine if self._state == 0: # waiting for menu pin being pressed. if (buttonLevel == self._buttonPressed): self._state = 1 self._startTime = now # remember starting time elif self._state == 1: # waiting for menu pin being released. if (buttonLevel == self._buttonReleased) and (ticks_diff(self._startTime,now) < self._debounceTicks): # button was released to quickly so I assume some debouncing. # go back to state 0 without calling a function. self._state = 0 elif buttonLevel == self._buttonReleased: self._state = 2 elif (buttonLevel == self._buttonPressed) and (ticks_diff(self._startTime,now) > self._pressTicks): self._isLongPressed = True; # Keep track of long press state if self._longPressStartFunc: self._longPressStartFunc(self) if self._duringLongPressFunc: self._duringLongPressFunc(self) self._state = 6 else: # wait. Stay in this state. pass elif self._state == 2: # waiting for menu pin being pressed the second time or timeout. if ticks_diff(self._startTime, now) > self._clickTicks: # this was only a single short click if self._clickFunc: self._clickFunc(self) self._state = 0 elif buttonLevel == self._buttonPressed: self._state = 3 elif self._state == 3: # waiting for menu pin being released finally. if buttonLevel == self._buttonReleased: # this was a 2 click sequence. if self._doubleClickFunc: self._doubleClickFunc(self) self._state = 0 elif self._state == 6: # waiting for menu pin being release after long press. if buttonLevel == self._buttonReleased: self._isLongPressed = False if self._longPressStopFunc: self._longPressStopFunc(self) self._state = 0 else: # button is being long pressed self._isLongPressed = True if self._duringLongPressFunc: self._duringLongPressFunc(self)
# Start the thread, you need this line gpsThread = L76micropyGPS.startGPSThread() print("startGPSThread thread id is: {}".format(gpsThread)) # # Do what you like now, examples below # at some point you should want to read GPS/GNS data # you need none of these lines, but I would assume # at least one line doing something with my_gps object ... # #start rtc rtc = machine.RTC() print("Free Mem post rtc instantiation: {}".format(gc.mem_free())) start = utime.ticks_ms() print("RTC time : {}".format(rtc.now())) print('Aquiring GPS signal ', end='') #try to get gps date to config rtc # # Just and example while thread to spit out # GPS/GNS data to the console/uart # while (True): print("my_gps.parsed_sentences: {}".format(my_gps.parsed_sentences)) print("my_gps.satellites_in_use: {}".format(my_gps.satellites_in_use)) print("my_gps.date: {}".format(my_gps.date)) print("my_gps.timestamp: {}".format(my_gps.timestamp)) timestamp = my_gps.timestamp dt = my_gps.time_since_fix()/1000
miso=fm.fpioa.GPIOHS14, sclk=fm.fpioa.GPIOHS15) HW_ESP32 = True except: print('HAL ESP32 FAILED') try: sensor.reset() sensor.set_pixformat(sensor.RGB565) sensor.set_framesize(sensor.QVGA) sensor.skip_frames(time=2000) HW_CAMERA = True except: print('HAL CAMERA FAILED') millis = utime.ticks_ms() while True: if button.value() == 0: while button.value() == 0: pass lcd_rotation += 1 lcd_rotation %= 4 lcd.rotation(lcd_rotation) status = 0 x = 0 y = 0 if HW_TOUCH: (status, x, y) = ts.read() if (status == ts.STATUS_PRESS or status == ts.STATUS_MOVE):
def MQTT_Connect(self): # Check if Wifi is up if self.wlan0.isconnected() == False: return # Will check if we publishe the ip here since we dont run a loop for wifi if self.wlan0_Published_IP == False: # Log ip self.Log(0, 'WiFi', 'Got IP: ' + str(self.wlan0.ifconfig()[0])) # Mark we did so self.wlan0_Published_IP = True # Check if we are connected if self.MQTT_State == True: return # 5 sec between reconnect attepts if utime.ticks_diff(utime.ticks_ms(), self.MQTT_Reconnect_At) < 5000: return # Save when we last tried to connect so we can check agains it self.MQTT_Reconnect_At = utime.ticks_ms() Error = None # Try to connect to MQTT try: self.MQTT_Client.connect() except OSError as e: # Get Error number Error = int(str(e).split(" ")[1].replace("]", "")) # Check if it matches the current state, aka nothing changed if self.MQTT_State != Error: # No change since last connection attempt ## Warning since initial connection attempt failed if self.MQTT_State == 'init': self.Log( 2, 'System', 'Unable to connect to broker: ' + str(self.Config['MQTT_Broker'])) elif Error in [103, 104]: self.Log( 2, 'System', 'Disconnected from broker: ' + str(self.Config['MQTT_Broker'])) else: self.Log(2, 'System', 'MQTT Error: ' + str(e)) # MQTT Username and pass issue except MQTT.MQTTException as e: Error = str(e) # Check if it matches the current state, aka nothing changed if self.MQTT_State != Error: # Incorect useranem and password if str(e) == "5": self.Log(2, 'System', 'Incorrect username and password') Error = "5" else: self.Log(2, 'System', "Unknown error - Exception: " + str(e)) Error = True # except: # self.Log(2, 'System', 'Unknown error') # Error = True finally: if Error != None: # Check if IndicatorLED is enabeled if self.Sys_Modules.get('IndicatorLED', None) != None: # Turn on MQTT blink self.Sys_Modules['IndicatorLED'].Enable('MQTT') # Set self.MQTT_State = Error so we can check if it changed later in life self.MQTT_State = Error # return after error return # print('self.MQTT_Client.ping()') # print(self.MQTT_Client.ping()) # Check if IndicatorLED is enabeled if self.Sys_Modules.get('IndicatorLED', None) != None: # Turn off MQTT blink self.Sys_Modules['IndicatorLED'].Disable('MQTT') # When we get to here we should be connected self.MQTT_State = True # if we connected to mqtt empyth the log checks the connection state self.Log_Queue_Empyhy() # Log event self.Log(1, 'MQTT', 'Connected to MQTT Broker: ' + self.Config['MQTT_Broker']) # Register on mqtt message callback self.MQTT_Client.set_callback(self.MQTT_On_Message) # Subscribe to topics for Topic in self.MQTT_Subscribe_To: # Subscribe self.MQTT_Subscribe(Topic)
def get_ticks_ms(): if is_micropython(): return utime.ticks_ms() else: return int(dt.datetime.timestamp(dt.datetime.now()) * 1000)
def timeout(seconds): start = utime.ticks_ms() while True: yield utime.ticks_ms() - start >= seconds * 1000
client = connect_and_subscribe(sub_topic_stat_PRI) except OSError as e: restart_and_reconnect() while True: try: client.check_msg() if (utime.time() - last_message) > message_interval: JsonMqtt = ujson.dumps(mqttJson) if IsBilgePumpDev: pubtopic = topic_pub + sub_topic_status client.publish(pubtopic, JsonMqtt) elif IsslampherDev: PRIState = Pin(PRI_pin, Pin.IN).value() if PRIState == 1 and mqttJson["PRI"] == 'Off': # motion start = utime.ticks_ms() mqttJson["PRI"] = 'On' led_on() pubtopic = topic_pub + sub_topic_power client.publish(pubtopic, PRIStateOn) elif PRIState == 0 and mqttJson["PRI"] == 'On': end = utime.ticks_diff(utime.ticks_ms(), start) print(end / 1000) mqttJson["PRI"] = 'Off' led_off() pubtopic = topic_pub + sub_topic_power client.publish(pubtopic, PRIStateOff) print("PRI State is ", PRIState) pubtopic = topic_pub + sub_topic_stat_PRI JsonMqtt = ujson.dumps(mqttJson) client.publish(pubtopic, JsonMqtt)
def handle(self, task: Task) -> None: deadline = utime.ticks_add(utime.ticks_ms(), self.delay_ms) schedule(task, deadline, deadline)
def power_up(points): points = min(25, points + 1) for i in range(3): music.pitch(200 + i * 10 + 10 * points, duration=20, pin=pin2) redraw_points(points) return points def redraw_points(points): for i in range(25): display.set_pixel(i % 5, int(i / 5), 9 if points > i else 0) prev = utime.ticks_ms() points = 2 redraw_points(points) def get_delay(points): return 600 - (points - 5) * 15 got_missile = False def plot_ship(ship, missile): colour = constants.MISSILE_COLOUR if missile.got_missile( ) else constants.SHIP_COLOUR
# This file is executed on every boot (including wake-boot from deepsleep) #import esp #esp.osdebug(None) #import webrepl #webrepl.start() import network import utime from credenciales import ssid, password red = network.WLAN(network.STA_IF) red.active(True) red.connect(ssid, password) while not red.isconnected(): utime.sleep_ms(50) if utime.ticks_ms() > 10000: # timeout de 10 segundos print("ERROR no se ha podido conectar a la wifi {}".format(ssid)) break else: print(red.ifconfig())
def _timeout(self, t): return ticks_diff(ticks_ms(), t) > self._response_time
print("Receive Mode") timer = 0 timerTest = 0 pycom.rgbled(0xFF0000) utime.sleep(0.2) pycom.rgbled(0x000000) utime.sleep(0.2) pycom.rgbled(0xFF0000) utime.sleep(0.2) pycom.rgbled(0x000000) utime.sleep(0.2) s.setblocking(False) while True: timer = utime.ticks_ms() if (timer - timerTest > 5000): pycom.rgbled(0x000000) else: pycom.rgbled(0x00FF00) utime.sleep(0.2) pycom.rgbled(0x000000) utime.sleep(0.2) pycom.rgbled(0x00FF00) utime.sleep(0.2) pycom.rgbled(0x000000) utime.sleep(0.2) # Receive data data = s.recv(64) print(data)
def fork(self) -> None: self.deadline_ms = utime.ticks_ms() + _CONFIRM_STATE_TIMEOUT_MS self.task = self.confirm() workflow.onstart(self.task) loop.schedule(self.task)
# Turn off everything: #gps.send_command('PMTK314,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0') # Tuen on everything (not all of it is parsed!) #gps.send_command('PMTK314,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0') # Set update rate to once a second (1hz) which is what you typically want. gps.send_command('PMTK220,1000') # Or decrease to once every two seconds by doubling the millisecond value. # Be sure to also increase your UART timeout above! #gps.send_command('PMTK220,2000') # You can also speed up the rate, but don't go too fast or else you can lose # data during parsing. This would be twice a second (2hz, 500ms delay): #gps.send_command('PMTK220,500') # Main loop runs forever printing the location, etc. every second. last_print = time.ticks_ms() while True: # Make sure to call gps.update() every loop iteration and at least twice # as fast as data comes from the GPS unit (usually every second). # This returns a bool that's true if it parsed new data (you can ignore it # though if you don't care and instead look at the has_fix property). gps.update() # Every second print out current location details if there's a fix. current = time.ticks_ms() if time.ticks_diff(last_print, current) >= 1000: last_print = current if not gps.has_fix: # Try again if we don't have a fix yet. print('Waiting for fix...') continue
def start(self): self.start_ticks_ms = utime.ticks_ms() ui.display.bar(0, 32, 240, 240 - 80, ui.BG)