Python utime.ticks_us() Examples
The following are 30
code examples of utime.ticks_us().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
utime
, or try the search function
.
Example #1
Source File: demo_sprite.py From micropython-ssd1351 with MIT License | 7 votes |
def test(): """Bouncing sprite.""" try: # Baud rate of 14500000 seems about the max spi = SPI(2, baudrate=14500000, sck=Pin(18), mosi=Pin(23)) display = Display(spi, dc=Pin(17), cs=Pin(5), rst=Pin(16)) display.clear() # Load sprite logo = BouncingSprite('images/Python41x49.raw', 41, 49, 128, 128, 1, display) while True: timer = ticks_us() logo.update_pos() logo.draw() # Attempt to set framerate to 30 FPS timer_dif = 33333 - ticks_diff(ticks_us(), timer) if timer_dif > 0: sleep_us(timer_dif) except KeyboardInterrupt: display.cleanup()
Example #2
Source File: _legoBoard.py From UIFlow-Code with GNU General Public License v3.0 | 6 votes |
def update(self): if time.ticks_us() >= self.interval: self.interval = time.ticks_us() + 10000 if not self.angle_point == None: self.input_value = self.encoder_read() - self.enc_zero output_value = self.angle_pid.get_pid(self.input_value, self.angle_point) self.set_pwm(output_value) if not self.speed_point == None: # Encoder filter self.input_value *= 0.75 self.input_value += self.encoder_incr() * 0.25 # self.input_value = constrain(self.input_value, -30, 30) # Output pwm output_value = self.speed_pid.get_pid(self.input_value, self.speed_point) self.set_pwm(output_value) # print("in:%0.2f, out:%0.2f\r\n" % (self.input_value, output_value))
Example #3
Source File: as_tGPS.py From micropython-async with MIT License | 6 votes |
def get_t_split(self): state = machine.disable_irq() t = self.t_ms acquired = self.acquired machine.enable_irq(state) isecs, ims = divmod(t, 1000) # Get integer secs and ms x, secs = divmod(isecs, 60) hrs, mins = divmod(x, 60) dt = utime.ticks_diff(utime.ticks_us(), acquired) # μs to time now ds, us = divmod(dt, 1000000) # If dt > 1e6 can add to secs without risk of rollover: see above. self._time[0] = hrs self._time[1] = mins self._time[2] = secs + ds self._time[3] = us + ims*1000 return self._time
Example #4
Source File: profile.py From rubiks-color-resolver with MIT License | 6 votes |
def timed_function(f, *args, **kwargs): #myname = str(f).split(' ')[1] def new_func(*args, **kwargs): #t = utime.ticks_us() result = f(*args, **kwargs) #if myname not in profile_stats_time_including_children: # profile_stats_time_including_children[myname] = 0 # profile_stats_calls[myname] = 0 #profile_stats_time_including_children[myname] += utime.ticks_diff(utime.ticks_us(), t) #profile_stats_calls[myname] += 1 return result return new_func
Example #5
Source File: dftclass.py From micropython-fourier with MIT License | 6 votes |
def run(self, conversion): # Uses assembler for speed if self.popfunc is not None: self.popfunc(self) # Populate the data (for fwd transfers, just the real data) if conversion != REVERSE: # Forward transform: real data assumed setarray(self.im, 0, self._length)# Fast zero imaginary data if self.windata is not None: # Fast apply the window function winapply(self.re, self.windata, self._length) start = utime.ticks_us() fft(self.ctrl, conversion) delta = utime.ticks_diff(utime.ticks_us(), start) if (conversion & POLAR) == POLAR: # Ignore complex conjugates, convert 1st half of arrays topolar(self.re, self.im, self._length//2) # Fast if conversion == DB: # Ignore conjugates: convert 1st half only for idx, val in enumerate(self.re[0:self._length//2]): self.re[idx] = -80.0 if val <= 0.0 else 20*math.log10(val) - self.dboffset return delta # Subclass for acquiring data from Pyboard ADC using read_timed() method.
Example #6
Source File: deltat.py From micropython-fusion with MIT License | 6 votes |
def __call__(self, ts): if self.expect_ts: if ts is None: raise ValueError('Timestamp expected but not supplied.') else: if is_micropython: ts = time.ticks_us() else: raise RuntimeError('Not MicroPython: provide timestamps and a timediff function') # ts is now valid if self.start_time is None: # 1st call: self.start_time is invalid self.start_time = ts return 0.0001 # 100μs notional delay. 1st reading is invalid in any case dt = self.timediff(ts, self.start_time) self.start_time = ts return dt
Example #7
Source File: as_tGPS.py From micropython-async with MIT License | 6 votes |
def get_t_split(self): state = machine.disable_irq() t = self.t_ms acquired = self.acquired machine.enable_irq(state) isecs, ims = divmod(t, 1000) # Get integer secs and ms x, secs = divmod(isecs, 60) hrs, mins = divmod(x, 60) dt = utime.ticks_diff(utime.ticks_us(), acquired) # μs to time now ds, us = divmod(dt, 1000000) # If dt > 1e6 can add to secs without risk of rollover: see above. self._time[0] = hrs self._time[1] = mins self._time[2] = secs + ds self._time[3] = us + ims*1000 return self._time
Example #8
Source File: aremote.py From micropython-async with MIT License | 5 votes |
def _cb_pin(self, line): t = ticks_us() # On overrun ignore pulses until software timer times out if self._edge <= _EDGECOUNT: # Allow 1 extra pulse to record overrun if not self._ev_start.is_set(): # First edge received self._ev_start.set(ticks_ms()) # asyncio latency compensation self._times[self._edge] = t self._edge += 1
Example #9
Source File: stepper.py From uPySensors with Apache License 2.0 | 5 votes |
def step(self, steps_to_move, speed=None, hold=True): if speed is not None: self.set_speed(speed) steps_left = abs(steps_to_move) if steps_to_move > 0: direction = 1 else: direction = 0 while steps_left > 0: now = utime.ticks_us() if now - self._last_step_time >= self._step_delay: self._last_step_time = now if direction == 1: self._step_number += 1 if direction == 0: if self._step_number == 0: self._step_number == steps_left self._step_number -= 1 self.step_motor(self._step_number % 4) steps_left -= 1 if self._step_number == steps_left: self._step_number = 0 if steps_left == 0 and not hold: self.release()
Example #10
Source File: asi2c_i.py From micropython-async with MIT License | 5 votes |
def _run(self): while True: # If hardware link exists reboot Responder await self.reboot() self.txbyt = b'' self.rxbyt = b'' await self._sync() await asyncio.sleep(1) # Ensure Responder is ready if self.cr_go: self.loop.create_task(self.cr_go(*self.go_args)) while True: gc.collect() try: tstart = utime.ticks_us() self._sendrx() t = utime.ticks_diff(utime.ticks_us(), tstart) except OSError: # Reboot remote. break await asyncio.sleep_ms(Initiator.t_poll) self.block_max = max(self.block_max, t) # self measurement self.block_cnt += 1 self.block_sum += t self.nboots += 1 if self.cr_fail: await self.cr_fail(*self.f_args) if self.reset is None: # No means of recovery raise OSError('Responder fail.')
Example #11
Source File: as_GPS_time.py From micropython-async with MIT License | 5 votes |
def us_cb(my_gps, tick, led): global us_acquired # Time of previous PPS edge in ticks_us() if us_acquired is not None: # Trigger Message. Pass time between PPS measured by utime.ticks_us() tick.set(utime.ticks_diff(my_gps.acquired, us_acquired)) us_acquired = my_gps.acquired led.toggle() # Setup initialises with above callback
Example #12
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _isr(self, _): acquired = utime.ticks_us() # Save time of PPS # Time in last NMEA sentence was time of last PPS. # Reduce to integer secs since midnight local time. isecs = (self.epoch_time + int(3600*self.local_offset)) % 86400 # ms since midnight (28 bits). Add in any ms in RMC data msecs = isecs * 1000 + self.msecs # This PPS is presumed to be one update later msecs += self._update_ms if msecs >= 86400000: # Next PPS will deal with rollover return if self.t_ms == msecs: # No RMC message has arrived: nothing to do return self.t_ms = msecs # Current time in ms past midnight self.acquired = acquired # Set RTC if required and if last RMC indicated a 1 second boundary if self._rtc_set: # Time as int(seconds) in last NMEA sentence. Earlier test ensures # no rollover when we add 1. self._rtcbuf[6] = (isecs + 1) % 60 rtc.datetime(self._rtcbuf) self._rtc_set = False # Could be an outage here, so PPS arrives many secs after last sentence # Is this right? Does PPS continue during outage? self._pps_cb(self, *self._pps_cb_args) # Called when base class updates the epoch_time. # Need local time for setting Pyboard RTC in interrupt context
Example #13
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _await_pps(self): t0 = self.acquired while self.acquired == t0: # Busy-wait on PPS interrupt: not time-critical await asyncio.sleep_ms(0) # because acquisition time stored in ISR. gc.collect() # Time-critical code follows st = rtc.datetime()[7] while rtc.datetime()[7] == st: # Wait for RTC to change (4ms max) pass dt = utime.ticks_diff(utime.ticks_us(), self.acquired) trtc = self._get_rtc_usecs() - dt # Read RTC now and adjust for PPS edge tgps = 1000000 * (self.epoch_time + 3600*self.local_offset + 1) return trtc, tgps # Non-realtime calculation of calibration factor. times are in μs
Example #14
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def get_ms(self): state = machine.disable_irq() t = self.t_ms acquired = self.acquired machine.enable_irq(state) return t + utime.ticks_diff(utime.ticks_us(), acquired) // 1000 # Return accurate GPS time of day (hrs: int, mins: int, secs: int, μs: int) # The ISR can skip an update of .secs if a day rollover would occur. Next # RMC handles this, so if updates are at 1s intervals the subsequent ISR # will see hms = 0, 0, 1 and a value of .acquired > 1000000. # Even at the slowest update rate of 10s this can't overflow into minutes.
Example #15
Source File: as_rwGPS_time.py From micropython-async with MIT License | 5 votes |
def us_cb(my_gps, tick, led): global us_acquired if us_acquired is not None: # Trigger event. Pass time between PPS measured by utime.ticks_us() tick.set(utime.ticks_diff(my_gps.acquired, us_acquired)) us_acquired = my_gps.acquired led.toggle() # Setup initialises with above callback
Example #16
Source File: alcdtest.py From micropython-async with MIT License | 5 votes |
def lcd_task(): for secs in range(20, -1, -1): lcd[0] = 'MicroPython {}'.format(secs) lcd[1] = "{:11d}uS".format(time.ticks_us()) await asyncio.sleep(1)
Example #17
Source File: pin_cb_test.py From micropython-async with MIT License | 5 votes |
def toggle(_): global t pinout.value(not pinout.value()) t = utime.ticks_us() # Callback for basic test
Example #18
Source File: pin_cb_test.py From micropython-async with MIT License | 5 votes |
def cbl(pinin): global max_latency dt = utime.ticks_diff(utime.ticks_us(), t) max_latency = max(max_latency, dt) print('Latency {:6d}μs {:6d}μs max'.format(dt, max_latency))
Example #19
Source File: latency.py From micropython-async with MIT License | 5 votes |
def priority(): global tmax, tmin, dtotal, count device = DummyDeviceDriver() while True: await after(0) # Ensure low priority coros get to run tstart = time.ticks_us() await device # Measure the latency delta = time.ticks_diff(time.ticks_us(), tstart) tmax = max(tmax, delta) tmin = min(tmin, delta) dtotal += delta count += 1
Example #20
Source File: as_GPS_time.py From micropython-async with MIT License | 5 votes |
def us_cb(my_gps, tick, led): global us_acquired # Time of previous PPS edge in ticks_us() if us_acquired is not None: # Trigger event. Pass time between PPS measured by utime.ticks_us() tick.set(utime.ticks_diff(my_gps.acquired, us_acquired)) us_acquired = my_gps.acquired led.toggle() # Setup initialises with above callback
Example #21
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _isr(self, _): acquired = utime.ticks_us() # Save time of PPS # Time in last NMEA sentence was time of last PPS. # Reduce to integer secs since midnight local time. isecs = (self.epoch_time + int(3600*self.local_offset)) % 86400 # ms since midnight (28 bits). Add in any ms in RMC data msecs = isecs * 1000 + self.msecs # This PPS is presumed to be one update later msecs += self._update_ms if msecs >= 86400000: # Next PPS will deal with rollover return if self.t_ms == msecs: # No RMC message has arrived: nothing to do return self.t_ms = msecs # Current time in ms past midnight self.acquired = acquired # Set RTC if required and if last RMC indicated a 1 second boundary if self._rtc_set: # Time as int(seconds) in last NMEA sentence. Earlier test ensures # no rollover when we add 1. self._rtcbuf[6] = (isecs + 1) % 60 rtc.datetime(self._rtcbuf) self._rtc_set = False # Could be an outage here, so PPS arrives many secs after last sentence # Is this right? Does PPS continue during outage? self._pps_cb(self, *self._pps_cb_args) # Called when base class updates the epoch_time. # Need local time for setting Pyboard RTC in interrupt context
Example #22
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def _await_pps(self): t0 = self.acquired while self.acquired == t0: # Busy-wait on PPS interrupt: not time-critical await asyncio.sleep_ms(0) # because acquisition time stored in ISR. gc.collect() # Time-critical code follows st = rtc.datetime()[7] while rtc.datetime()[7] == st: # Wait for RTC to change (4ms max) pass dt = utime.ticks_diff(utime.ticks_us(), self.acquired) trtc = self._get_rtc_usecs() - dt # Read RTC now and adjust for PPS edge tgps = 1000000 * (self.epoch_time + 3600*self.local_offset + 1) return trtc, tgps # Non-realtime calculation of calibration factor. times are in μs
Example #23
Source File: as_tGPS.py From micropython-async with MIT License | 5 votes |
def get_ms(self): state = machine.disable_irq() t = self.t_ms acquired = self.acquired machine.enable_irq(state) return t + utime.ticks_diff(utime.ticks_us(), acquired) // 1000 # Return accurate GPS time of day (hrs: int, mins: int, secs: int, μs: int) # The ISR can skip an update of .secs if a day rollover would occur. Next # RMC handles this, so if updates are at 1s intervals the subsequent ISR # will see hms = 0, 0, 1 and a value of .acquired > 1000000. # Even at the slowest update rate of 10s this can't overflow into minutes.
Example #24
Source File: as_rwGPS_time.py From micropython-async with MIT License | 5 votes |
def us_cb(my_gps, tick, led): global us_acquired if us_acquired is not None: # Trigger event. Pass time between PPS measured by utime.ticks_us() tick.set(utime.ticks_diff(my_gps.acquired, us_acquired)) us_acquired = my_gps.acquired led.toggle() # Setup initialises with above callback
Example #25
Source File: aremote.py From micropython-async with MIT License | 5 votes |
def _cb_pin(self, line): t = ticks_us() # On overrun ignore pulses until software timer times out if self._edge <= _EDGECOUNT: # Allow 1 extra pulse to record overrun if not self._ev_start.is_set(): # First edge received loop = asyncio.get_event_loop() self._ev_start.set(loop.time()) # asyncio latency compensation self._times[self._edge] = t self._edge += 1
Example #26
Source File: _m5bala.py From UIFlow-Code with GNU General Public License v3.0 | 5 votes |
def __init__(self, i2c=None): if i2c is None: self.i2c = i2c_bus.get(i2c_bus.M_BUS) else: self.i2c = i2c self.imu = MPU6050(self.i2c) if self.i2c.is_ready(M5GO_WHEEL_ADDR) or self.i2c.is_ready(M5GO_WHEEL_ADDR): pass else: raise ImportError("Bala Motor not connect") self.id = self.imu.whoami # self.set_motor(0, 0) self.imu.setGyroOffsets(-2.71, -0.01, -0.04) self.loop_interval = time.ticks_us() self.dt = time.ticks_us() self.angleX = 0 self.angleX_offset = 0 self.last_angle = 0.0 self.last_wheel = 0.0 self.in_speed0 = 0 self.in_speed1 = 0 self.left = 0 self.right = 0 self.K1 = 40 self.K2 = 40 self.K3 = 6.5 self.K4 = 5.5 self.K5 = 0 self.enc_filter = 0.90
Example #27
Source File: mpu6050.py From UIFlow-Code with GNU General Public License v3.0 | 5 votes |
def ypr(self): """ yaw, pitch, roll as floats. """ accX, accY, accZ = self.acceleration angleAccX = math.atan2(accY, accZ + abs(accX)) * SF_RAD_S angleAccY = math.atan2(accX, accZ + abs(accY)) * (-SF_RAD_S); gyroX, gyroY, gyroZ = self.gyro gyroX -= self.gyroXoffset gyroY -= self.gyroYoffset gyroZ -= self.gyroZoffset interval = (time.ticks_us() - self.preInterval) / 1000000 self.preInterval = time.ticks_us() self.angleGyroX += gyroX * interval self.angleGyroY += gyroY * interval self.angleGyroZ += gyroZ * interval self.angleX = (self.gyroCoef * (self.angleX + gyroX * interval)) + (self.accCoef * angleAccX); self.angleY = (self.gyroCoef * (self.angleY + gyroY * interval)) + (self.accCoef * angleAccY); self.angleZ = self.angleGyroZ return tuple([round(self.angleZ, 3), round(self.angleX, 3), round(self.angleY, 3)])
Example #28
Source File: asi2c_i.py From micropython-iot with MIT License | 5 votes |
def _run(self): while True: # If hardware link exists reboot Responder await self.reboot() self.txbyt = b'' self.rxbyt = b'' await self._sync() await asyncio.sleep(1) # Ensure Responder is ready if self.cr_go: asyncio.create_task(self.cr_go(*self.go_args)) while True: gc.collect() try: tstart = utime.ticks_us() self._sendrx() t = utime.ticks_diff(utime.ticks_us(), tstart) except OSError: # Reboot remote. break await asyncio.sleep_ms(Initiator.t_poll) self.block_max = max(self.block_max, t) # self measurement self.block_cnt += 1 self.block_sum += t self.nboots += 1 if self.cr_fail: await self.cr_fail(*self.f_args) if self.reset is None: # No means of recovery raise OSError('Responder fail.')
Example #29
Source File: demo_bouncing_boxes.py From micropython-ssd1351 with MIT License | 5 votes |
def test(): """Bouncing box.""" try: # Baud rate of 14500000 seems about the max spi = SPI(2, baudrate=14500000, sck=Pin(18), mosi=Pin(23)) display = Display(spi, dc=Pin(17), cs=Pin(5), rst=Pin(16)) display.clear() colors = [color565(255, 0, 0), color565(0, 255, 0), color565(0, 0, 255), color565(255, 255, 0), color565(0, 255, 255), color565(255, 0, 255)] sizes = [12, 11, 10, 9, 8, 7] boxes = [Box(128, 128, sizes[i], display, colors[i]) for i in range(6)] while True: timer = ticks_us() for b in boxes: b.update_pos() b.draw() # Attempt to set framerate to 30 FPS timer_dif = 33333 - ticks_diff(ticks_us(), timer) if timer_dif > 0: sleep_us(timer_dif) except KeyboardInterrupt: display.cleanup()
Example #30
Source File: dftclass.py From micropython-fourier with MIT License | 5 votes |
def run(self, conversion, duration): tim = self.timer tim.deinit() tim.init(freq = int(self._length/duration)) self.adc.read_timed(self.buff, tim) # Note: blocks for duration start = utime.ticks_us() icopy(self.buff, self.re, self._length) # Fast copy integer array into real super().run(conversion) return utime.ticks_diff(utime.ticks_us(), start)