def master(): fut = Future() self.assertEqual((yield from x(10, 'happy')), 'happy') self.assertEqual((yield from w(x(10, 'pleased'), fut)), 'pleased') self.assertEqual(fut.result(), 'pleased') #logging.basicConfig(level=logging.DEBUG) #log.debug("Now %f", self.loop.time()) # One that completes before the timeout t0 = pyb.millis() fut = Future() self.loop.call_soon(w(x(20, 'good'), fut)) v = yield from wait_for(fut, 50) self.assertEqual(v, 'good') et = pyb.elapsed_millis(t0) self.assertTrue(20 <= et < 25, 'et was %rms (expected 20-25ms)' % et) # One that hits the timeout t0 = pyb.millis() fut = Future() self.loop.call_soon(w(x(20, 'fine'), fut)) with self.assertRaises(TimeoutError): v = yield from wait_for(fut, 10) et = pyb.elapsed_millis(t0) self.assertTrue(10 <= et < 15, 'et was %rms (expected 10-15ms)' % et)
def makegauge(self): ''' Generator refreshing the raw measurments. ''' delays = (5, 8, 14, 25) while True: self._bmp_i2c.mem_write(0x2E, self._bmp_addr, 0xF4) t_start = pyb.millis() while pyb.elapsed_millis(t_start) <= 5: # 5mS delay yield None try: self.UT_raw = self._bmp_i2c.mem_read(2, self._bmp_addr, 0xF6) except: yield None self._bmp_i2c.mem_write((0x34 + (self.oversample_setting << 6)), self._bmp_addr, 0xF4) t_pressure_ready = delays[self.oversample_setting] t_start = pyb.millis() while pyb.elapsed_millis(t_start) <= t_pressure_ready: yield None try: self.MSB_raw = self._bmp_i2c.mem_read(1, self._bmp_addr, 0xF6) self.LSB_raw = self._bmp_i2c.mem_read(1, self._bmp_addr, 0xF7) self.XLSB_raw = self._bmp_i2c.mem_read(1, self._bmp_addr, 0xF8) except: yield None yield True
def appFun(): timeStart = pyb.millis() timeCheck = pyb.millis() while (True): nowTime = pyb.elapsed_millis(timeStart) if nowTime % 1000 > 1: pyb.LED(RED_LED_PIN).off() elif nowTime > 1000: pyb.LED(RED_LED_PIN).on() timeStart = pyb.millis() val = uartRx() if val != -1: pyb.LED(RED_LED_PIN).off() if val == CMD_USER1: registerUser(1) elif val == CMD_USER2: registerUser(2) elif val == CMD_USER3: registerUser(3) elif val == CMD_CLEAR: clearUsers() else: deltaTime = pyb.elapsed_millis(timeCheck) if deltaTime > 500: pyb.LED(RED_LED_PIN).off() timeCheck = pyb.millis() checkUser()
def makegauge(self): ''' Generator refreshing the raw measurments. ''' delays = (5, 8, 14, 25) while True: self._bmp_i2c.mem_write(0x2E, self._bmp_addr, 0xF4) t_start = pyb.millis() while pyb.elapsed_millis(t_start) <= 5: # 5mS delay yield None try: self.UT_raw = self._bmp_i2c.mem_read(2, self._bmp_addr, 0xF6) except: yield None self._bmp_i2c.mem_write((0x34+(self.oversample_setting << 6)), self._bmp_addr, 0xF4) t_pressure_ready = delays[self.oversample_setting] t_start = pyb.millis() while pyb.elapsed_millis(t_start) <= t_pressure_ready: yield None try: self.MSB_raw = self._bmp_i2c.mem_read(1, self._bmp_addr, 0xF6) self.LSB_raw = self._bmp_i2c.mem_read(1, self._bmp_addr, 0xF7) self.XLSB_raw = self._bmp_i2c.mem_read(1, self._bmp_addr, 0xF8) except: yield None yield True
def blink(self, relais): if pyb.elapsed_millis(self.blink_start) < self.blink_time: relais.low() else: relais.high() if pyb.elapsed_millis(self.blink_start) > 2 * self.blink_time: self.blink_start = pyb.millis()
def face_recog(calc_time, vi_ip): pin = pyb.millis() print(pin) print(calc_time) cc = 0 #pyb.elapsed_millis(start) while pyb.elapsed_millis(pin) < calc_time: print("top of face recog function") #snapshot on face detection RED_LED_PIN = 1 BLUE_LED_PIN = 3 sensor.reset() # Initialize the camera sensor. sensor.set_contrast(3) sensor.set_gainceiling(16) sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.HQVGA) # or sensor.QQVGA (or others) #sensor.alloc_extra_fb() sensor.skip_frames(time=2000) # Let new settings take affect. face_cascade = image.HaarCascade("frontalface", stages=25) uos.chdir("/") pyb.LED(RED_LED_PIN).on() print("About to start detecting faces...") sensor.skip_frames(time=2000) # Give the user time to get ready. pyb.LED(RED_LED_PIN).off() print("Now detecting faces!") pyb.LED(BLUE_LED_PIN).on() diff = 10 # We'll say we detected a face after 10 frames. try: while (diff): img = sensor.snapshot() sensor.alloc_extra_fb(img.width(), img.height(), sensor.GRAYSCALE) faces = img.find_features(face_cascade, threshold=0.5, scale_factor=1.5) sensor.dealloc_extra_fb() if faces: diff -= 1 for r in faces: img.draw_rectangle(r) elif (pyb.elapsed_millis(pin)) > calc_time: raise Exception pyb.LED(BLUE_LED_PIN).off() print("Face detected! Saving image...") pic_name = "snapshot-person.pgm" sensor.snapshot().save( pic_name) # Save Pic. to root of SD card -- uos.chdir("/") pyb.delay(100) facial_recog(pic_name, vi_ip) gc.collect() except Exception as go: print("we are in exception") pyb.LED(BLUE_LED_PIN).off() gc.collect()
def face_detect(init_start, calc_time): print("~~~~~~~~~~~~~~~~FACE_DETECT~~~~~~~~~~~~~~~~~~~~~~") gc.collect() #garbage collection while pyb.elapsed_millis(init_start) < calc_time: #while time not expired #snapshot on face detection RED_LED_PIN = 1 BLUE_LED_PIN = 3 sensor.reset() # Initialize the camera sensor. sensor.set_contrast(3) #set to highest contrast setting sensor.set_gainceiling(16) sensor.set_pixformat( sensor.GRAYSCALE) #grayscale for facial recognition sensor.set_framesize(sensor.HQVGA) sensor.skip_frames(time=2000) # Let new settings take affect. face_cascade = image.HaarCascade( "frontalface", stages=25) #Using Frontal Face Haar Cascade Classifier uos.chdir("/") pyb.LED(RED_LED_PIN).on() print("About to start detecting faces...") sensor.skip_frames(time=2000) # Give the user time to get ready. pyb.LED(RED_LED_PIN).off() print("Now detecting faces!") pyb.LED(BLUE_LED_PIN).on() diff = 10 # We'll say we detected a face after 10 frames. try: while (diff): img = sensor.snapshot() sensor.alloc_extra_fb( img.width(), img.height(), sensor.GRAYSCALE) #allocate more space for image faces = img.find_features( face_cascade, threshold=0.5, scale_factor=1.5) #detecting face features sensor.dealloc_extra_fb() if faces: diff -= 1 for r in faces: img.draw_rectangle(r) elif (pyb.elapsed_millis(init_start) ) > calc_time: #if time is expired, leave function raise Exception pyb.LED(BLUE_LED_PIN).off() print("Face detected! Saving image...") pic_name = "snapshot-person.pgm" sensor.snapshot().save(pic_name) # Save Pic. to root of SD card pyb.delay(100) gc.collect() #garbage collection return pic_name except Exception as go: print("exception - time expired") pyb.LED(BLUE_LED_PIN).off() gc.collect() #garbage collection
def blink_millis(): start = pyb.millis() led.on() while pyb.elapsed_millis(start) < 100: pass led.off() while pyb.elapsed_millis(start) < 200: pass led.on() while pyb.elapsed_millis(start) < 300: pass led.off() while pyb.elapsed_millis(start) < 1000: pass
def task(self): self.task_conn() if self.last_http_time > 0 and pyb.elapsed_millis( self.last_http_time) > 10000: self.kick() return STS_KICKED if self.last_http_time < 0 and self.full_reboot_timer > 0 and pyb.elapsed_millis( self.full_reboot_timer) > 12000: self.reboot() return STS_KICKED x = self.task_dns() y = self.task_http() if x == STS_SERVED or y == STS_SERVED: return STS_SERVED return STS_IDLE
def __get_command(self, timeout): # private self._put_short_timeout = self._put_short_timeout_reset self._get_short_timeout = self._get_short_timeout_reset start = pyb.millis() while pyb.elapsed_millis(start) < timeout: gc.collect() # Avoid collection during the transfer. self._zero(self.__in_command_header_buf[0], len(self.__in_command_header_buf[0])) self._flush() packet = self._get_packet(self._COMMAND_HEADER_PACKET_MAGIC, self.__in_command_header_buf, self._get_short_timeout) if packet is not None: command, datalen = struct.unpack("<II", packet) in_command_data_buf = self._get_packet_pre_alloc(datalen) self.put_bytes(self.__out_command_header_ack, self._put_short_timeout) dat_packet = self._get_packet(self._COMMAND_DATA_PACKET_MAGIC, in_command_data_buf, self._get_long_timeout) if dat_packet is not None: self.put_bytes(self.__out_command_data_ack, self._put_short_timeout) return (command, dat_packet) # Avoid timeout livelocking. self._put_short_timeout = min(self._put_short_timeout + 1, timeout) self._get_short_timeout = min(self._get_short_timeout + 1, timeout) return (None, None)
def run_igniter_test(base_pin_name='Y12'): pin = pyb.Pin(base_pin_name, pyb.Pin.OUT_PP) pin.low() lcd = LCD160CR('X') lcd.set_orient(PORTRAIT_UPSIDEDOWN) lcd.set_text_color(lcd.rgb(255, 0, 0), lcd.rgb(0, 0, 0)) lcd.set_font(3) lcd.erase() countdown = 15000 remaining = countdown start = pyb.millis() while True: remaining = countdown - pyb.elapsed_millis(start) if remaining <= 0: break lcd.erase() lcd.set_pos(40, 80) lcd.write('{:.2f}'.format(remaining / 1000)) pyb.delay(51) lcd.erase() pin.high() lcd.set_pos(40, 80) lcd.write('BOOM !!!') pin.low()
def wait(self, delay): t0 = pyb.millis() if delay == 0: return if delay == -1: # if delay == -1 the queue got emptied without stopping the loop blue_led.on() return blue_led.off() self._led.on() ust = pyb.micros() # Do possibly useful things in our idle time if delay > 6: gct0 = pyb.micros() gc.collect() # we have the time, so might as well clean up self.max_gc_us = max(pyb.elapsed_micros(gct0), self.max_gc_us) while pyb.elapsed_millis(t0) < delay: # Measure the idle time # Anything interesting at this point will require an interrupt # If not some pin or peripheral or user timer, then it will be # the 1ms system-tick interrupt, which matches our wait resolution. # So we can save power by waiting for interrupt. pyb.wfi() self.idle_us += pyb.elapsed_micros(ust) self._led.off()
def adcread(chan): # 16 temp 17 vbat 18 vref bounds(chan, 16, 18, 'Invalid ADC channel') start = pyb.millis() timeout = 100 stm.mem32[stm.RCC + stm.RCC_APB2ENR] |= 0x100 # enable ADC1 clock.0x4100 stm.mem32[stm.ADC1 + stm.ADC_CR2] = 1 # Turn on ADC stm.mem32[stm.ADC1 + stm.ADC_CR1] = 0 # 12 bit if chan == 17: stm.mem32[stm.ADC1 + stm.ADC_SMPR1] = 0x200000 # 15 cycles channel 17 stm.mem32[stm.ADC + 4] = 1 << 23 elif chan == 18: stm.mem32[stm.ADC1 + stm.ADC_SMPR1] = 0x1000000 # 15 cycles channel 18 0x1200000 stm.mem32[stm.ADC + 4] = 0xc00000 else: stm.mem32[stm.ADC1 + stm.ADC_SMPR1] = 0x40000 # 15 cycles channel 16 stm.mem32[stm.ADC + 4] = 1 << 23 stm.mem32[stm.ADC1 + stm.ADC_SQR3] = chan stm.mem32[stm.ADC1 + stm.ADC_CR2] = 1 | (1 << 30) | (1 << 10) # start conversion while not stm.mem32[stm.ADC1 + stm.ADC_SR] & 2: # wait for EOC if pyb.elapsed_millis(start) > timeout: raise OSError('ADC timout') data = stm.mem32[stm.ADC1 + stm.ADC_DR] # clears down EOC stm.mem32[stm.ADC1 + stm.ADC_CR2] = 0 # Turn off ADC return data
def __put_result(self, data, timeout): # private self._put_short_timeout = self._put_short_timeout_reset self._get_short_timeout = self._get_short_timeout_reset out_header = self._set_packet(self._RESULT_HEADER_PACKET_MAGIC, struct.pack("<I", len(data))) out_data = self._set_packet(self._RESULT_DATA_PACKET_MAGIC, data) start = pyb.millis() while pyb.elapsed_millis(start) < timeout: gc.collect() # Avoid collection during the transfer. self._zero(self.__in_response_header_buf[0], len(self.__in_response_header_buf[0])) self._zero(self.__in_response_data_buf[0], len(self.__in_response_data_buf[0])) self._flush() if self._get_packet(self._RESULT_HEADER_PACKET_MAGIC, self.__in_response_header_buf, self._get_short_timeout) is not None: self.put_bytes(out_header, self._put_short_timeout) if self._get_packet(self._RESULT_DATA_PACKET_MAGIC, self.__in_response_data_buf, self._get_short_timeout) is not None: self.put_bytes(out_data, self._put_long_timeout) return True # Avoid timeout livelocking. self._put_short_timeout = min(self._put_short_timeout + 1, timeout) self._get_short_timeout = min(self._get_short_timeout + 1, timeout) return False
def process(self): self.update() if pyb.elapsed_millis(self.counter) >= self.timeout: self.hrp = [self.fuse.heading, self.fuse.roll, self.fuse.pitch] self.counter = pyb.millis() return True return False
def __get_result(self, timeout): # private self._put_short_timeout = self._put_short_timeout_reset self._get_short_timeout = self._get_short_timeout_reset start = pyb.millis() while pyb.elapsed_millis(start) < timeout: gc.collect() # Avoid collection during the transfer. self._zero(self.__in_result_header_buf[0], len(self.__in_result_header_buf[0])) self._flush() self.put_bytes(self.__out_result_header_ack, self._put_short_timeout) packet = self._get_packet(self._RESULT_HEADER_PACKET_MAGIC, self.__in_result_header_buf, self._get_short_timeout) if packet is not None: in_result_data_buf = self._get_packet_pre_alloc( struct.unpack("<I", packet)[0]) self.put_bytes(self.__out_result_data_ack, self._put_short_timeout) dat_packet = self._get_packet(self._RESULT_DATA_PACKET_MAGIC, in_result_data_buf, self._get_long_timeout) if dat_packet is not None: return dat_packet # Avoid timeout livelocking. self._put_short_timeout = min((self._put_short_timeout * 4) // 3, timeout) self._get_short_timeout = min((self._get_short_timeout * 4) // 3, timeout) return None
def _frame_fixed_timed(self, fixed_value, stage_time): t_start = pyb.millis() t_elapsed = -1 while t_elapsed < stage_time: for line in range(LINES_PER_DISPLAY - 1, -1, -1): self._line_fixed(line, fixed_value, set_voltage_limit=False) t_elapsed = pyb.elapsed_millis(t_start)
def fp_speed(n = 80000): x = 1.1 t1 = pyb.millis() while n != 0: x += 0.1 n -= 1 print ("Elapsed ", pyb.elapsed_millis(t1))
def _frame_fixed_timed(self, fixed_value, stage_time): t_start = pyb.millis() t_elapsed = -1 while t_elapsed < stage_time: for line in range(LINES_PER_DISPLAY -1, -1, -1): self._line_fixed(line, fixed_value, set_voltage_limit = False) t_elapsed = pyb.elapsed_millis(t_start)
def fp_speed(n=80000): x = 1.1 t1 = pyb.millis() while n != 0: x += 0.1 n -= 1 print("Elapsed ", pyb.elapsed_millis(t1))
def face_detect(init_start, calc_time): print("~~~~~~~~~~~~~~~~FACE_DETECT~~~~~~~~~~~~~~~~~~~~~~") gc.collect() while pyb.elapsed_millis(init_start) < calc_time: RED_LED_PIN = 1 BLUE_LED_PIN = 3 sensor.reset() sensor.set_contrast(3) sensor.set_gainceiling(16) sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.HQVGA) sensor.skip_frames(time=2000) face_cascade = image.HaarCascade("frontalface", stages=25) uos.chdir("/") pyb.LED(RED_LED_PIN).on() print("About to start detecting faces...") sensor.skip_frames(time=2000) pyb.LED(RED_LED_PIN).off() print("Now detecting faces!") pyb.LED(BLUE_LED_PIN).on() diff = 10 try: while (diff): img = sensor.snapshot() sensor.alloc_extra_fb(img.width(), img.height(), sensor.GRAYSCALE) faces = img.find_features(face_cascade, threshold=0.5, scale_factor=1.5) sensor.dealloc_extra_fb() if faces: diff -= 1 for r in faces: img.draw_rectangle(r) elif (pyb.elapsed_millis(init_start)) > calc_time: raise Exception pyb.LED(BLUE_LED_PIN).off() print("Face detected! Saving image...") pic_name = "snapshot-person.pgm" sensor.snapshot().save(pic_name) pyb.delay(100) gc.collect() return pic_name except Exception as go: print("exception - time expired") pyb.LED(BLUE_LED_PIN).off() gc.collect()
def send_buffer(disp, n=1000): disp.framebuf.fill(0) start = pyb.millis() for i in range(n): disp.send_buffer() return pyb.elapsed_millis(start)
def send(self, buf, timeout=500): send_nonblock = self.send_start(buf) start = pyb.millis() result = None while result is None and pyb.elapsed_millis(start) < timeout: result = self.send_done() # 1 == success, 2 == fail if result == 2: raise OSError("send failed")
def verify_write(self, data, timeout=500): timeout /= 2 start_time = millis() while elapsed_millis(start_time) < timeout: self.write_encode(data) val = self.read_timeout(timeout) if val == str(data): return val
def speed(): x = 1 n = 800000 t1 = pyb.millis() while n != 0: x += 1 n -= 1 print ("Elapsed ", pyb.elapsed_millis(t1))
def put_bytes(self, data, timeout_ms): # protected start = pyb.millis() while(self.__pin.value()): if pyb.elapsed_millis(start) >= self._put_short_timeout: return self.__spi.init(pyb.SPI.SLAVE, polarity=self.__polarity, phase=self.__clk_phase) try: self.__spi.send(data, timeout=timeout_ms) except OSError: pass self.__spi.deinit()
def speed(): x = 1 n = 800000 t1 = pyb.millis() while n != 0: x += 1 n -= 1 print("Elapsed ", pyb.elapsed_millis(t1))
def get_bytes(self, buff, timeout_ms): # protected start = pyb.millis() while(self.__pin.value()): if pyb.elapsed_millis(start) >= self._get_short_timeout: return None self.__spi.init(pyb.SPI.SLAVE, polarity=self.__polarity, phase=self.__clk_phase) try: self.__spi.send_recv(buff, buff, timeout=timeout_ms) # SPI.recv() is broken. except OSError: buff = None self.__spi.deinit() return buff
def await_message(self, msg_rx): start = pyb.millis() while pyb.elapsed_millis(start) <= self.timeout: try: if self.get_latest_msg(msg_rx): return True except OSError: pass # Bad message length. Try again. return False # Timeout
def snapshot_check(self): if self.snap_started == False: return False if self.simulate: dt = pyb.elapsed_millis(self.sim_t) if dt > (self.shutter // 1000): return True else: return False return sensor.snapshot_check()
def master(lcd): yield Roundrobin() m = rp.Master(config_master) obj = [0, ''] x = ord('a') while True: start = pyb.millis() try: result = m.exchange(obj) t = pyb.elapsed_millis(start) except OSError: t = pyb.elapsed_millis(start) lcd[0] = 'Timeout' else: lcd[0] = str(result) finally: lcd[1] = 't = {}mS'.format(t) yield from wait(1.0) obj[0] += 1
def frame_fixed_repeat(self, fixed_value, stage): start = pyb.millis() count = 0 while True: self.frame_fixed(fixed_value, stage) count +=1 if pyb.elapsed_millis(start) > self.factored_stage_time: break if self.verbose: print('frame_fixed_repeat count = {}'.format(count))
def frame_fixed_repeat(self, fixed_value, stage): start = pyb.millis() count = 0 while True: self.frame_fixed(fixed_value, stage) count += 1 if pyb.elapsed_millis(start) > self.factored_stage_time: break if self.verbose: print('frame_fixed_repeat count = {}'.format(count))
def __init__(self): # Initializing self.switch = pyb.Switch() self.start_led = pyb.LED(2) self.sensor_base = SensorBase.SensorBase() # Constants self.sampling_delay = 6 #ms delay self.standard_delay = 500 #ms self.test_time = 30000 #ms # Flicker to indicate start of test for i in range(3): self.start_led.on() pyb.delay(self.standard_delay) self.start_led.off() pyb.delay(self.standard_delay) while not self.switch(): pass log = open('/sd/06_02_17_raw_walk_random.csv', 'w') pyb.delay(self.standard_delay) self.start_time = pyb.millis() time = 0 self.start_led.on() while not self.switch() and time < self.test_time: # TODO Sample and record gravity ax, ay, az, gx, gy, gz, mx, my, mz, yaw, roll, pitch = self.sensor_base.sample_motion( ) fsr1, fsr2, fsr3 = self.sensor_base.sample_fsr() time = pyb.elapsed_millis(self.start_time) # ax = 0 if (abs(ax) < 1) else ax # ay = 0 if (abs(ay) < 1) else ay # az = 0 if (abs(az) < 1) else az # print("ax: {} \t ay: {} \t , az: {}".format(ax, ay, az)) # print("fsr1: {} \t fsr2: {} \t , fsr3: {}".format(fsr1, fsr2, fsr3)) log.write( '{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n'.format( time, ax, ay, az, gx, gy, gz, mx, my, mz, roll, pitch, yaw, fsr1, fsr2, fsr3)) # log.write('{},{},{}, {}\n'.format(time, ax, ay, az)) pyb.delay(self.sampling_delay) log.close() # Flicker to indicate end of test # self.start_led.on() # pyb.delay(self.standard_delay) self.start_led.off()
def pulse(self, duration_ms): startTime = pyb.millis() while (duration_ms < 0 or pyb.elapsed_millis(startTime) < duration_ms): self.set_pw_colors(pyb.millis() / 1000, self.red_channel, self.green_channel, self.blue_channel) pyb.udelay(self.led_timer.period()) self.led_timer.deinit() self.red_led_off(None) self.green_led_off(None) self.blue_led_off(None)
def debug(step): print('temps (s)\n') while True: senBMP() senMPU() datalog() t = pyb.elapsed_millis(start) / 1000 #print('{},{},{},{},{},{},{},{},{},{},{},{}\n'.format(t,p,altitud,acX,acY,acZ,gX,gY,gZ,mX,mY,mZ)) print('{}, {}, {}\n'.format(t, altitud, mag)) time.sleep_ms(step)
def process(self): if self.seq_idx >= 0 and pyb.elapsed_millis(self.last_toggle) > self.sequence[self.seq_idx]: self.led.toggle() self.last_toggle = pyb.millis() self.seq_idx += 1 if self.seq_idx >= len(self.sequence): if self.continuous: self.seq_idx = 0 else: self.seq_idx = -1 self.led.off() # Just in case we got an odd length
def run(self): self.screen.update(self.battery1, self.battery2) self.last_write = time() screen_timer = pyb.millis() while True: # Update battery data and screen every 10 seconds if pyb.elapsed_millis(screen_timer) > 10000: screen_timer = self.update() self.log_test() gc.collect() self.CMD.Poll()
def frame_data_repeat(self, stage, use_old): self.asm_data[0] = addressof(self.image) self.asm_data[1] = addressof(self.image_old) if use_old else 0 start = pyb.millis() count = 0 while True: self.frame_data(stage) count +=1 if pyb.elapsed_millis(start) > self.factored_stage_time: break if self.verbose: print('frame_data_repeat count = {}'.format(count))
def check_idle(self): check = False if self.get_channel(1) < 250: if self.start_timer > 0: if pyb.elapsed_millis(self.start_timer) > 5000: # 5 sec check = True self.start_timer = 0 else: self.start_timer = pyb.millis() else: self.start_timer = 0 return check
def check_arming(self): check = False if self.get_channel(1) < 250 and self.get_channel(3) < 250 and self.get_channel(4) > 1600: if self.start_timer > 0: if pyb.elapsed_millis(self.start_timer) > 3000: # 3 sec check = True self.start_timer = 0 else: self.start_timer = pyb.millis() else: self.start_timer = 0 return check
def master(): nrf = NRF24L01(SPI(2), Pin('Y5'), Pin('Y4'), 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 = pyb.millis() 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 = pyb.millis() timeout = False while not nrf.any() and not timeout: if pyb.elapsed_millis(start_time) > 250: timeout = True if timeout: print('failed, respones 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', pyb.millis() - got_millis, 'ms)') num_successes += 1 # delay then loop pyb.delay(250) print('master finished sending; succeses=%d, failures=%d' % (num_successes, num_failures))
def master(): t0 = pyb.millis() fut = Future() me = yield GetRunningCoro(None) self.assertEqual(self.loop.q, []) # nobody in the queue yield from sleep(1) self.assertEqual(self.loop.q, []) # nobody in the queue v_coro = yield coro(me, 10) # starts self.assertEqual(len(self.loop.q), 1) # coro is queued v_sleep = yield Sleep(20) et = pyb.elapsed_millis(t0) # We got send()'ed to when the coro finished, before the Sleep self.assertTrue(10 <= et < 15, 'et was %rms' % et) self.assertEqual(v_sleep, 'coro-scheduled')
def await_message(self, allowed_cmds): start_time = pyb.millis() while not self.any(): if pyb.elapsed_millis(start_time) > self.timeout: raise OSError # Timeout inbuf = self.get_latest_msg() if inbuf is None or len(inbuf) < MSGSTART: raise OSError cmd = inbuf[0] & MASK if cmd not in allowed_cmds: raise CommandException # Unexpected response nbytes = inbuf[BYTECOUNT] # Received bytes if nbytes: # Can receive zero length messages (responses to tx) self.inlist.append(inbuf[MSGSTART: MSGSTART + nbytes].decode('utf8')) # List of received strings return inbuf[0], nbytes
def master(lcd): yield Roundrobin() m = rf.Master(testbox_config) send_msg = FromMaster() while True: start = pyb.millis() result = m.exchange(send_msg) t = pyb.elapsed_millis(start) lcd[1] = "t = {}mS".format(t) if result is not None: lcd[0] = str(result.i0) else: lcd[0] = "Timeout" yield from wait(1.0) send_msg.i0 += 1
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 assuming using millis on a pyboard; default to seconds if not try: current = pyb.elapsed_millis(self.fix_time) except NameError: current = time.time() - self.fix_time return current
def current(self): a = self.Afunc.read(self.AfuncArg) self.A = -a + self.Aoffset AHtemp = self.A * pyb.elapsed_millis(self.timer) / 3600000 self.AH += AHtemp # set current AH value and adjust if beyond limits if self.AH < 0: self.AH = 0 elif self.AH > self.Battery_AH_Capacity: self.AH = self.Battery_AH_Capacity # TODO: is a 24 hour more useful or 60 min running? self.AH_15 += AHtemp self.AH_60 += AHtemp self.AH_day += AHtemp self.timer = pyb.millis()
def update(self): self.V = randrange(118, 138)/10 self.A = randrange(-40, 40)/10 AHtemp = self.A * pyb.elapsed_millis(self.timer) / 3600000 self.AH += AHtemp # set current AH value and adjust if beyond limits if self.AH < 0: self.AH = 0 elif self.AH > self.Battery_AH_Capacity: self.AH = self.Battery_AH_Capacity self.AH_15 += AHtemp self.AH_60 += AHtemp self.AH_day += AHtemp self.timer = pyb.millis() self.capacity()
def doFlag (line): """ This is called when a flag (line) is found to be True: - if there hasn't been enough time, reset flag and return - otherwise - toggle the corresponding led - reset the flag to false - print a message """ global ledPins,flagVec,eVec,lastInterT # if not enough time, reset flag and return flagVec[line] = False if elapsed_millis(lastInterT) < debounceDelay: return lastInterT = millis() ledPins[line].value(ledPins[line].value()^1) print('LED: ',line, 'toggled to:',ledPins[line].value(), '\ttime:', lastInterT)
def handle(self, button_value): if button_value == 0: if self.iostate is True: self.iostate = False self.relay.off() else: self.iostate = True self.relay.on() if self.state == self.STATE_BUTTON_START: self.start_time = pyb.millis() self.state = self.STATE_BUTTON_COLLECT self.events = list() self.timer = esp.os_timer(lambda timer: self.timer_finish(), period=self.period, repeat=False) elapsed = 0 else: elapsed = pyb.elapsed_millis(self.start_time) self.events.append((button_value, elapsed))
def get_packet(self, timeout=100): # Get a packet from the radio # or raise PacketWaitTimeout if none available in specified time def get_packet_by_reading(): # Helper to get a packet from the radio itself # Note it will spin forever if the radio has no packet self.nSSEL.low() gotten = 0 while len(self.pb) == 0 and gotten < 300: # feed the packet buffer until packet(s) available self.pb.include_bytes(self.spi.recv(self.rx_hunk_len)) # DEBUG gotten += self.rx_hunk_len if self.verbose: print("get_packet_by_reading(): State %d, gotten %d, marking bytes %d, total marking %d" % (self.pb.state, gotten, self.pb.marking_bytes_count, self.pb.total_marking_bytes_count)) if gotten >= 300: raise PacketOverrunError("got %d bytes and don't have a packet yet" % gotten) return self.pb.dequeue_one() # From the packet buffer if available if len(self.pb): return self.pb.dequeue_one() # else if part way into a packet, get the rest if self.pb.in_a_packet(): return get_packet_by_reading() # else see if one turns up within the timeout if self.nATTN.value(): # No data available from radio yet # wait up to the timeout value t0 = millis() while self.nATTN.value(): if elapsed_millis(t0) > timeout: raise PacketWaitTimeout("%dms" % timeout) #delay(self.delay_after_nATTN) # Does this help? No. # Here nATTN is in asserted state # drop thru instead: return get_packet_by_reading() assert not self.nATTN.value(), 'expected nATTN to be low' #delay(10) # DEBUG: does this help? return get_packet_by_reading()
def callback(line): """ toggle the pin corresponding to the switch """ eVec[line].disable() global interCount,lastGoodInterrupt if elapsed_millis(lastGoodInterrupt) < interruptDelay: print("poo!") eVec[line].enable() return if sPins[line].value(): print('piii!') eVec[line].enable() return print(interCount,': Interrupt received: ',switchPosNames[line]) #, 'pin value: ', sPins[e].value()) ledPins[0].value(ledPins[0].value()^1) interCount +=1 lastGoodInterrupt=millis() eVec[line].enable()
def update(self,round_time): self.rpm_count+=1 self.rpm_times+=round_time if elapsed_millis(self.last_update)>self.update_interval: rpm=self.rpm_count/self.rpm_times*60000000 self.v=self.get_speed(self.v) P=self.get_power(self.v) max_tc,max_tr=self.max31885.read() self.tft.update(rpm=rpm, bmp_tr=self.bmp180.temperature, bmp_press=self.bmp180.pressure/1000, max_tr=max_tr, max_tc=max_tc, time_frame=round_time/4, velocity=self.v, gear=self.get_gear(), torque=self.get_torque(P,rpm), power=P) self.rpm_count=0 self.rpm_times=0 self.last_update=millis()
def slave(lcd): yield Roundrobin() s = rf.Slave(testbox_config) # Slave on testbox send_msg = ToMaster() while True: while True: start = pyb.millis() result = s.exchange(send_msg, block=False) t = pyb.elapsed_millis(start) yield Roundrobin() if result is None: # Timeout break if result: # Success break if result is None: lcd[0] = "Timeout" elif result: lcd[0] = str(result.i0) lcd[1] = "t = {}mS".format(t) yield Roundrobin() send_msg.i0 += 1
def sendbuf(self, radio, cmd): radio.stop_listening() # Flush buffers start_time = pyb.millis() self.outbuf[COMMAND] = cmd if cmd == RESEND or cmd == BYE: # Bye and Resend request have no data self.outbuf[BYTECOUNT] = 0 else: self.outbuf[BYTECOUNT] = self.bytes_tx if self.txleft == 0: self.outbuf[COMMAND] |= TXDONE sent = False while not sent: try: radio.send(self.outbuf, timeout=radio.timeout) sent = True except OSError: # send timed out. pass # It may have returned early. Try again if so. finally: if pyb.elapsed_millis(start_time) >= radio.timeout: radio.start_listening() raise OSError radio.start_listening()