Python utime.ticks_diff() Examples

The following are 30 code examples of utime.ticks_diff(). 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 vote down vote up
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: cantest.py    From micropython-async with MIT License 6 votes vote down vote up
def run_cancel_test6(loop):
    for name in ('complete', 'cancel me'):
        loop.create_task(asyn.NamedTask(name, cant60, name)())
    loop.create_task(asyn.Cancellable(cant61)())
    await asyncio.sleep(4.5)
    print('Cancelling task \"{}\". 1.5 secs latency.'.format(name))
    await asyn.NamedTask.cancel(name)
    await asyncio.sleep(7)
    name = 'cancel wait'
    loop.create_task(asyn.NamedTask(name, cant60, name)())
    await asyncio.sleep(0.5)
    print('Cancelling task \"{}\". 1.5 secs latency.'.format(name))
    t = time.ticks_ms()
    await asyn.NamedTask.cancel('cancel wait', nowait=False)
    print('Was cancelled in {} ms'.format(time.ticks_diff(time.ticks_ms(), t)))
    print('Cancelling cant61')
    await asyn.Cancellable.cancel_all()
    print('Done') 
Example #3
Source File: dftclass.py    From micropython-fourier with MIT License 6 votes vote down vote up
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 #4
Source File: as_tGPS.py    From micropython-async with MIT License 6 votes vote down vote up
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 #5
Source File: server.py    From micropython-samples with MIT License 6 votes vote down vote up
def readline(s, timeout):
    line = b''
    start = utime.ticks_ms()
    while True:
        if line.endswith(b'\n'):
            if len(line) > 1:
                return line
            line = b''
            start = utime.ticks_ms()  # A blank line is just a  keepalive
        await asyncio.sleep_ms(100)  # See note above
        d = s.readline()
        if d == b'':
            raise OSError
        if d is not None:
            line = b''.join((line, d))
        if utime.ticks_diff(utime.ticks_ms(), start) > timeout:
            raise OSError 
Example #6
Source File: client_w.py    From micropython-samples with MIT License 6 votes vote down vote up
def readline(self):
        line = b''
        start = utime.ticks_ms()
        while True:
            if line.endswith(b'\n'):
                if len(line) > 1:
                    return line
                line = b''
                start = utime.ticks_ms()  # Blank line is keepalive
                self.led(not self.led())
            await asyncio.sleep_ms(100)  # nonzero wait seems empirically necessary
            d = self.sock.readline()
            if d == b'':
                raise OSError
            if d is not None:
                line = b''.join((line, d))
            if utime.ticks_diff(utime.ticks_ms(), start) > self.timeout:
                raise OSError 
Example #7
Source File: mqtt_as.py    From micropython-mqtt with MIT License 6 votes vote down vote up
def broker_up(self):  # Test broker connectivity
        if not self.isconnected():
            return False
        tlast = self.last_rx
        if ticks_diff(ticks_ms(), tlast) < 1000:
            return True
        try:
            await self._ping()
        except OSError:
            return False
        t = ticks_ms()
        while not self._timeout(t):
            await asyncio.sleep_ms(100)
            if ticks_diff(self.last_rx, tlast) > 0:  # Response received
                return True
        return False 
Example #8
Source File: eddystone.py    From uble with MIT License 6 votes vote down vote up
def adcread(chan): # 16 temp 17 vbat 18 vref
    assert chan >= 16 and chan <= 18, 'Invalid ADC channel'
    start = utime.ticks_ms()
    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
        stm.mem32[stm.ADC + 4] = 1 << 23
    elif chan == 18:
        stm.mem32[stm.ADC1 + stm.ADC_SMPR1] = 0x1000000
        stm.mem32[stm.ADC + 4] = 0xc00000
    else:
        stm.mem32[stm.ADC1 + stm.ADC_SMPR1] = 0x40000
        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 utime.ticks_diff(utime.ticks_ms(), start) > timeout:
            raise OSError('ADC timout')
    data = stm.mem32[stm.ADC1 + stm.ADC_DR] # clear down EOC
    stm.mem32[stm.ADC1 + stm.ADC_CR2] = 0 # Turn off ADC
    return data 
Example #9
Source File: color96.py    From micropython-nano-gui with MIT License 6 votes vote down vote up
def multi_fields(t):
    print('multi_fields')
    refresh(ssd, True)  # Clear any prior image
    nfields = []
    dy = wri.height + 6
    y = 2
    col = 15
    width = wri.stringlen('99.99')
    for txt in ('X:', 'Y:', 'Z:'):
        Label(wri, y, 0, txt)  # Use wri default colors
        nfields.append(Label(wri, y, col, width, bdcolor=None))  # Specify a border, color TBD
        y += dy

    end = utime.ticks_add(utime.ticks_ms(), t * 1000)
    while utime.ticks_diff(end, utime.ticks_ms()) > 0:
        for field in nfields:
            value = int.from_bytes(uos.urandom(3),'little')/167772
            overrange =  None if value < 70 else YELLOW if value < 90 else RED
            field.value('{:5.2f}'.format(value), fgcolor = overrange, bdcolor = overrange)
        refresh(ssd)
        utime.sleep(1)
    Label(wri, 0, 64, ' OK ', True, fgcolor = RED)
    refresh(ssd)
    utime.sleep(1) 
Example #10
Source File: color15.py    From micropython-nano-gui with MIT License 6 votes vote down vote up
def multi_fields(t):
    print('Dynamic labels.')
    refresh(ssd, True)  # Clear any prior image
    nfields = []
    dy = wri.height + 6
    y = 2
    col = 15
    width = wri.stringlen('99.99')
    for txt in ('X:', 'Y:', 'Z:'):
        Label(wri, y, 0, txt)  # Use wri default colors
        nfields.append(Label(wri, y, col, width, bdcolor=None))  # Specify a border, color TBD
        y += dy

    end = utime.ticks_add(utime.ticks_ms(), t * 1000)
    while utime.ticks_diff(end, utime.ticks_ms()) > 0:
        for field in nfields:
            value = int.from_bytes(uos.urandom(3),'little')/167772
            overrange =  None if value < 70 else YELLOW if value < 90 else RED
            field.value('{:5.2f}'.format(value), fgcolor = overrange, bdcolor = overrange)
        refresh(ssd)
        utime.sleep(1)
    Label(wri, 0, 64, ' OK ', True, fgcolor = RED)
    refresh(ssd)
    utime.sleep(1) 
Example #11
Source File: lamp.py    From esp8266 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example #12
Source File: profile.py    From rubiks-color-resolver with MIT License 6 votes vote down vote up
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 #13
Source File: ms_timer.py    From micropython-async with MIT License 5 votes vote down vote up
def ioctl(self, req, arg):
        ret = MP_STREAM_ERROR
        if req == MP_STREAM_POLL:
            ret = 0
            if arg & MP_STREAM_POLL_RD:
                if utime.ticks_diff(utime.ticks_ms(), self.end) >= 0:
                    ret |= MP_STREAM_POLL_RD
        return ret 
Example #14
Source File: sr_init.py    From micropython-async with MIT License 5 votes vote down vote up
def initiator_task(channel):
    while True:
        so = ['test', 0, 0]
        for x in range(4):          # Test full duplex by sending 4 in succession
            so[1] = x
            channel.send(so)
            await asyncio.sleep_ms(0)
        while True:                 # Receive the four responses
            si = await channel.await_obj()  # Deal with queue
            if si is None:
                print('Timeout: restarting.')
                return
            print('initiator received', si)
            if si[1] == 3:          # received last one
                break
        while True:                 # At 2 sec intervals send an object and get response
            await asyncio.sleep(2)
            print('sending', so)
            channel.send(so)
            tim = ticks_ms()
            so = await channel.await_obj()  # wait for response
            duration = ticks_diff(ticks_ms(), tim)
            if so is None:
                print('Timeout: restarting.')
                return
            print('initiator received', so, 'timing', duration) 
Example #15
Source File: aswitch.py    From micropython-async with MIT License 5 votes vote down vote up
def _killer(self):
        twait = time.ticks_diff(self._tstop, time.ticks_ms())
        while twait > 0:  # Must loop here: might be retriggered
            await asyncio.sleep_ms(twait)
            if self._tstop is None:
                break  # Return if stop() called during wait
            twait = time.ticks_diff(self._tstop, time.ticks_ms())
        if self._running and self.func is not None:
            launch(self.func, self.args)  # Timed out: execute callback
        self._tstop = None  # killer not running
        self._running = False  # timer is stopped 
Example #16
Source File: asi2c_i.py    From micropython-async with MIT License 5 votes vote down vote up
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:
                    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.')

    # Send payload length (may be 0) then payload (if any) 
Example #17
Source File: pin_cb_test.py    From micropython-async with MIT License 5 votes vote down vote up
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 #18
Source File: rtc_time.py    From micropython-async with MIT License 5 votes vote down vote up
def ticks_diff(end, start):
        return ((end - start + _PERIOD_2) % _PERIOD) - _PERIOD_2 
Example #19
Source File: asi2c_i.py    From micropython-async with MIT License 5 votes vote down vote up
def waitfor(self, val):  # Wait for response for 1 sec
        tim = utime.ticks_ms()
        while not self.rem() == val:
            if utime.ticks_diff(utime.ticks_ms(), tim) > 1000:
                raise OSError 
Example #20
Source File: apoll.py    From micropython-async with MIT License 5 votes vote down vote up
def timed_out(self):                # Time since last change or last timeout report
        if time.ticks_diff(self.loop.time(), self.last_change) > self.timeout:
            self.last_change = self.loop.time()
            return True
        return False 
Example #21
Source File: apoll.py    From micropython-async with MIT License 5 votes vote down vote up
def poll(self):                     # Device is noisy. Only update if change exceeds a threshold
        xyz = [self.accelhw.x(), self.accelhw.y(), self.accelhw.z()]
        if self.dsquared(xyz) > Accelerometer.threshold_squared:
            self.coords = xyz
            self.last_change = self.loop.time()
            return 0
        return time.ticks_diff(self.loop.time(), self.last_change) 
Example #22
Source File: aremote.py    From micropython-async with MIT License 5 votes vote down vote up
def _decode(self):
        overrun = self._edge > _EDGECOUNT
        val = OVERRUN if overrun else BADSTART
        if not overrun:
            width = ticks_diff(self._times[1], self._times[0])
            if width > 4000:  # 9ms leading mark for all valid data
                width = ticks_diff(self._times[2], self._times[1])
                if width > 3000: # 4.5ms space for normal data
                    if self._edge < _EDGECOUNT:
                        # Haven't received the correct number of edges
                        val = BADBLOCK
                    else:
                        # Time spaces only (marks are always 562.5µs)
                        # Space is 1.6875ms (1) or 562.5µs (0)
                        # Skip last bit which is always 1
                        val = 0
                        for edge in range(3, _EDGECOUNT - 2, 2):
                            val >>= 1
                            if ticks_diff(self._times[edge + 1], self._times[edge]) > 1120:
                                val |= 0x80000000
                elif width > 1700: # 2.5ms space for a repeat code. Should have exactly 4 edges.
                    val = REPEAT if self._edge == 4 else BADREP
        addr = 0
        if val >= 0:  # validate. Byte layout of val ~cmd cmd ~addr addr
            addr = val & 0xff
            cmd = (val >> 16) & 0xff
            if addr == ((val >> 8) ^ 0xff) & 0xff:  # 8 bit address OK
                val = cmd if cmd == (val >> 24) ^ 0xff else BADDATA
                self._addr = addr
            else:
                addr |= val & 0xff00  # pass assumed 16 bit address to callback
                if self._extended:
                    val = cmd if cmd == (val >> 24) ^ 0xff else BADDATA
                    self._addr = addr
                else:
                    val = BADADDR
        if val == REPEAT:
            addr = self._addr  # Last valid addresss
        self._edge = 0  # Set up for new data burst and run user callback
        self._ev_start.clear()
        self._callback(val, addr, *self._args) 
Example #23
Source File: aremote.py    From micropython-async with MIT License 5 votes vote down vote up
def _run(self):
        loop = asyncio.get_event_loop()
        while True:
            await self._ev_start  # Wait until data collection has started
            # Compensate for asyncio latency
            latency = ticks_diff(loop.time(), self._ev_start.value())
            await asyncio.sleep_ms(self.block_time - latency)  # Data block should have ended
            self._decode()  # decode, clear event, prepare for new rx, call cb

    # Pin interrupt. Save time of each edge for later decode. 
Example #24
Source File: time.py    From Adafruit_Blinka with MIT License 5 votes vote down vote up
def monotonic():
        """A monotonically increasing time in seconds. No defined start time."""
        # Assumes that monotonic is called more frequently than the wraparound of micropython's
        # utime.ticks_ms()
        global _prev_ticks_ms, _total_ms  # pylint: disable=global-statement
        ticks_ms = utime.ticks_ms()
        _total_ms += utime.ticks_diff(ticks_ms, _prev_ticks_ms)
        _prev_ticks_ms = ticks_ms
        return _total_ms * 0.001 
Example #25
Source File: delay_ms.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def _timer(self, restart):
        if restart:  # Restore cached end time
            self._tstop = self._tsave
        try:
            twait = ticks_diff(self._tstop, ticks_ms())
            while twait > 0:  # Must loop here: might be retriggered
                await asyncio.sleep_ms(twait)
                twait = ticks_diff(self._tstop, ticks_ms())
            if self._func is not None:  # Timed out: execute callback
                self._retrn = launch(self._func, self._args)
        finally:
            self._tsave = self._tstop  # Save in case we restart.
            self._tstop = None  # timer is stopped 
Example #26
Source File: delay_ms.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def trigger(self, duration=0):  # Update end time
        now = ticks_ms()
        if duration <= 0:  # Use default set by constructor
            duration = self._duration
        self._retrn = None
        is_running = self()
        tstop = self._tstop  # Current stop time
        # Retriggering normally just updates ._tstop for ._timer
        self._tstop = ticks_add(now, duration)
        # Identify special case where we are bringing the end time forward
        can = is_running and duration < ticks_diff(tstop, now)
        if not is_running or can:
            schedule(self._do_trig, can) 
Example #27
Source File: bluenrg_ms.py    From uble with MIT License 5 votes vote down vote up
def hci_wait_event(self, evtcode=0, subevtcode=0, timeout=1000, retry=5):
        """
        Wait for event and filter it if needed
        """
        # Maximum timeout is 1 seconds
        start = utime.ticks_ms()
        while utime.ticks_diff(utime.ticks_ms(), start) <= min(timeout, 1000):
            event = self.read(retry=retry)
            if self.hci_verify(event) and isinstance(event, (bytearray, bytes)):
                hci_uart = HCI_UART.from_buffer(event)
                if hci_uart.pkt_type == HCI_EVENT_PKT:
                    hci_evt = HCI_EVENT.from_buffer(hci_uart.data)
                    if not evtcode and not subevtcode:
                        return hci_evt
                    if subevtcode:
                        if hci_evt.evtcode in (EVT_LE_META_EVENT, EVT_VENDOR):
                            if hci_evt.subevtcode == subevtcode:
                                return hci_evt
                            else:
                                raise ValueError("unexpected subevtcode")
                    if evtcode:
                        if hci_evt.evtcode == evtcode:
                            return hci_evt
                        else:
                            raise ValueError("unexpected evtcode")
                else:
                    raise TypeError("not HCI_EVENT_PKT")
            else:
                continue 
Example #28
Source File: bluenrg_ms.py    From uble with MIT License 5 votes vote down vote up
def run(self, callback=None, callback_time=1000):
        """
        BLE event loop

        Note: This function call __start__() when invoked and __stop__() when
              KeyboardInterrupt, StopIteration or an Exception
              is raised.

              __process__() called whenever there is an event to be processed
        """
        try:
            self.__start__()
            start = utime.ticks_ms()
            while True:
                event = self.read(retry=5)
                if self.hci_verify(event):
                    self.__process__(event)
                # user defined periodic callback
                if callable(callback) and utime.ticks_diff(
                        utime.ticks_ms(), start) >= callback_time:
                    callback()
                    start = utime.ticks_ms()

        except (KeyboardInterrupt, StopIteration) as ex:
            raise ex
        except Exception as ex:
            raise ex
        finally:
            self.__stop__() 
Example #29
Source File: task.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def loop(self) :
        if self._verbose :
            logging.info("TaskBase: loop starting.")
        while self.isRunning() :
            if not self.disabled :
                try :
                    self.num_calls += 1
                    start_ticks_us = utime.ticks_us()
                    result = self.perform()
                    self.ticks_us += utime.ticks_diff(utime.ticks_us(), start_ticks_us)
                    if not result:
                        return
                    self.last_retry_ms = None
                except Exception as e :
                    if not self.last_retry_ms :
                        self.last_retry_ms = 500
                    else :
                        self.last_retry_ms = min(self.sleep_ms, self.last_retry_ms * 2)
                    self.num_failures += 1
                    logging.info("An error occurred performing {}: {}".format(self, e))
                    sys.print_exception(e)
                await uasyncio.sleep_ms(self.sleep_ms if not self.last_retry_ms else self.last_retry_ms)
            else :
                await uasyncio.sleep_ms(914)
        self.state = TaskBase.STOPPED
        if self._verbose :
            logging.info("TaskBase: loop terminated.")
        return 
Example #30
Source File: controller.py    From esp8266 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_stats(self) :
        return {
            'gcd': self.gcd.stats(),
            'ntpd': self.ntpd.stats(),
            'lamp': self.lamp.stats(),
            'scheduler': self.scheduler.stats(),
            'uptime_ms': utime.ticks_diff(utime.ticks_ms(), self.start_ms)
        }