Python time.ticks_diff() Examples

The following are 30 code examples of time.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 time , or try the search function .
Example #1
Source File: wifi_led.py    From pysmartnode with MIT License 6 votes vote down vote up
def _loop(self):
        mqtt = config.getMQTT()
        mqtt.registerWifiCallback(self._wifiChanged)
        mqtt.registerConnectedCallback(self._reconnected)
        await self._flash(500, 1)
        sta = network.WLAN(network.STA_IF)
        st = time.ticks_ms()
        while True:
            while self._next:
                await self._flash(*self._next.pop(0))
                await asyncio.sleep(1)
            if time.ticks_diff(time.ticks_ms(), st) > 60000:  # heartbeat
                st = time.ticks_ms()
                if sta.isconnected():
                    await self._flash(20, 1)
                    await asyncio.sleep_ms(250)
                    await self._flash(20, 1)
                else:
                    await self._flash(500, 3)
            await asyncio.sleep_ms(500) 
Example #2
Source File: mqtt_as_timeout.py    From micropython-mqtt with MIT License 6 votes vote down vote up
def publish(self, topic, msg, retain=False, qos=0, timeout=None):
        task = None
        start = time.ticks_ms()
        while timeout is None or time.ticks_diff(time.ticks_ms(), start) < timeout:
            # Can't use wait_for because cancelling a wait_for would cancel _publishTimeout
            # Also a timeout in wait_for would cancel _publishTimeout without waiting for
            # the socket lock to be available, breaking mqtt protocol.
            if self._pub_task is None and task is None:
                task = asyncio.create_task(self._publishTimeout(topic, msg, retain, qos))
                self._pub_task = task
            elif task is not None:
                if self._pub_task != task:
                    return  # published
            await asyncio.sleep_ms(20)
        if task is not None:
            async with self.lock:
                task.cancel()
                return 
Example #3
Source File: weather.py    From esp32-weather-google-sheets with MIT License 6 votes vote down vote up
def check(self):
        current_time = time.ticks_ms()
        deadline = time.ticks_add(self.last_measurement, self.interval)
        if ((time.ticks_diff(deadline, current_time) <= 0) or (self.iterations == 0)):
            self.measure()
            self.iterations += 1
            self.last_measurement = current_time

# the following function, when added to the google sheet (Tools > Script editor) allows the
# formula uploaded in the "now" variable (see "measure(self)") to calculate a local timestamp
# from the epoch value loaded in column A of the inserted row
#
#function TIMESTAMP_TO_DATE(value) {
#  return new Date(value * 1000);
#}
# see the sheets.py file to set the ValueInputOption to USER_INPUT to avoid now string value being prefixed with a ' 
Example #4
Source File: __init__.py    From micropython-samples with MIT License 6 votes vote down vote up
def push_sorted(self, v, data):
        v.data = data

        if ticks_diff(data, ticks()) <= 0:
            cur = self.last
            if cur and ticks_diff(data, cur.data) >= 0:
                # Optimisation: can start looking from self.last to insert this item
                while cur.next and ticks_diff(data, cur.next.data) >= 0:
                    cur = cur.next
                v.next = cur.next
                cur.next = v
                self.last = cur
                return

        cur = self
        while cur.next and (not isinstance(cur.next.data, int) or ticks_diff(data, cur.next.data) >= 0):
            cur = cur.next
        v.next = cur.next
        cur.next = v
        if cur is not self:
            self.last = cur 
Example #5
Source File: bell.py    From pysmartnode with MIT License 6 votes vote down vote up
def __bell(self):
        while True:
            await self._event_bell
            diff = time.ticks_diff(time.ticks_ms(), self._last_activation)
            if diff > 10000:
                _log.error("Bell rang {!s}s ago, not activated ringing".format(diff / 1000))
                self._event_bell.clear()
                return
            else:
                on = await _mqtt.publish(self.topic(), "ON", qos=1, timeout=2,
                                         await_connection=False)
                await asyncio.sleep_ms(self._on_time)
                await _mqtt.publish(self.topic(), "OFF", qos=1, retain=True, await_connection=on)
                if config.RTC_SYNC_ACTIVE:
                    t = time.localtime()
                    await _mqtt.publish(_mqtt.getDeviceTopic("last_bell"),
                                        "{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(t[0], t[1],
                                                                                       t[2], t[3],
                                                                                       t[4], t[5]),
                                        qos=1, retain=True, timeout=2, await_connection=False)
                self._event_bell.clear()
                if diff > 500:
                    _log.warn("Bell rang {!s}ms ago, activated ringing".format(diff)) 
Example #6
Source File: debug.py    From pysmartnode with MIT License 6 votes vote down vote up
def overwatch(coro_name, threshold, asyncr=False):
    def func_wrapper(coro):
        if asyncr is True:
            raise TypeError("overwatch does not support coroutines")
            # as it makes not sense. a freeze would trigger every coroutine
        else:
            def wrapper(*args, **kwargs):
                startt = time.ticks_ms()
                res = coro(*args, **kwargs)
                if str(type(res)) == "<class 'generator'>":
                    _log.error("Coroutine in sync overwatch")
                endt = time.ticks_ms()
                diff = time.ticks_diff(endt, startt)
                if diff > threshold:
                    _log.error("Coro {!s} took {!s}ms, threshold {!s}ms".format(coro_name, diff, threshold))
                return res

            return wrapper

    return func_wrapper 
Example #7
Source File: cfilter.py    From py-mpu6050 with GNU General Public License v3.0 5 votes vote down vote up
def input(self, vals):
        now = time.ticks_ms()

        # unpack sensor readings
        accel_data = vals[0:3]
        gyro_data = vals[4:7]

        # convert accelerometer reading to degrees
        self.accel_pos = self.calculate_accel_pos(*accel_data)

        # if this is our first chunk of data, simply accept
        # the accelerometer reads and move on.
        if self.last == 0:
            self.filter_pos = self.gyro_pos = self.accel_pos
            self.last = now
            return

        # calculate the elapsed time (in seconds) since last data.
        # we need this because the gyroscope measures movement in
        # degrees/second.
        dt = time.ticks_diff(now, self.last)/1000
        self.last = now

        # calculate change in position from gyroscope readings
        gyro_delta = [i * dt for i in gyro_data]
        self.gyro_pos = [i + j for i, j in zip(self.gyro_pos, gyro_delta)]

        # pitch
        self.filter_pos[0] = (
            self.gyro_weight * (self.filter_pos[0] + gyro_delta[0])
            + (1-self.gyro_weight) * self.accel_pos[0])

        # roll
        self.filter_pos[1] = (
            self.gyro_weight * (self.filter_pos[1] + gyro_delta[1])
            + (1-self.gyro_weight) * self.accel_pos[1]) 
Example #8
Source File: i2c_connector.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        t = time.ticks_ms()
        # if self.suspend_start is not None \
        #        and time.ticks_diff(t,self.suspend_start) <= self.suspend_time:
        #    print("Bus access suspended.")
        if self.suspend_start is None \
                or time.ticks_diff(t, self.suspend_start) > self.suspend_time:
            self.suspend_start = None  # done waiting
            try:
                if self.msgq is not None:
                    self.port.writeto(self.addr, self.msgq)
                    self.msgq = None
                s = self.port.readfrom(self.addr, self.BUFFER_SIZE)
            except:
                print("Trouble accessing i2c.")
            else:
                if s[0] == 255 and s[1] == 255:  # illegal read
                    print("Got garbage, waiting 1s before accessing bus again.")
                    print("data:", s)
                    self.suspend_time = 1000  # take a break
                    self.suspend_start = time.ticks_ms();
                else:
                    count = s[0] * 256 + s[1]
                    if self.count != count:
                        l = s[2];
                        self.suspend_time = s[3];
                        # scale timer
                        if self.suspend_time & 128:
                            self.suspend_time = (self.suspend_time & 127) * 100
                            if self.suspend_time > 5000:  # should not happen
                                print("Garbage time -> waiting 1s before accessing bus again.")
                                print("data:", s)
                                self.suspend_time = 1000
                        if self.suspend_time > 0:
                            self.suspend_start = time.ticks_ms();
                            print("Bus suspend for", self.suspend_time, "ms requested.")
                        if l <= self.BUFFER_SIZE:  # discard if too big
                            self.count = count
                            self.current_value = s[4:4 + l]
                            return self.current_value
        return None 
Example #9
Source File: crypt_socket.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def receive(self, request=0, timeoutms=None):
        # receive into network buffer,
        # fill buffer once and decrypt
        # if request>0 wait blocking for request number of bytes (if timeout
        # given interrupt after timeoutms ms)
        # timeout==None: block
        # timeout==0: return immediately after trying to read something from
        #             network buffer
        # timeout>0: try for time specified to read something before returning
        #            this function always returns a pointer to the buffer and
        #            number of bytes read (could be 0)
        data = self.netbuf_in
        data_mv = self.netbuf_in_mv
        readbytes = 0
        start_t = ticks_ms()
        while readbytes < self.netbuf_size:
            try:
                if self.sock_read(data_mv[readbytes:readbytes + 1]):
                    readbytes += 1  # result was not 0 or none
                else:
                    if readbytes >= request:
                        break  # break if not blocking to request size
            except OSError as e:
                if len(e.args) > 0 \
                        and (e.args[0] == errno.EAGAIN
                             or e.args[0] == errno.ETIMEDOUT):
                    if readbytes >= request:
                        break  # break if not blocking to request size
                else:
                    raise
            if timeoutms is not None \
                    and ticks_diff(ticks_ms(), start_t) >= timeoutms:
                break
            sleep_ms(1)  # prevent busy waiting
        if readbytes > 0: self.crypt_in.decrypt(data, length=readbytes)
        return data, readbytes 
Example #10
Source File: micropython.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def monkeypatch_stdlib():

    import builtins
    builtins.const = int

    sys.modules['micropython'] = Mock()
    sys.modules['micropython'].const = int

    import struct
    sys.modules['ustruct'] = struct

    import binascii
    sys.modules['ubinascii'] = binascii

    import time
    def ticks_ms():
        import time
        return time.time() * 1000
    def ticks_diff(ticks1, ticks2):
        return abs(ticks1 - ticks2)
    time.ticks_ms = ticks_ms
    time.ticks_diff = ticks_diff
    sys.modules['utime'] = time

    import io
    sys.modules['uio'] = io

    import os
    sys.modules['uos'] = os

    import gc
    gc.threshold = Mock()
    gc.mem_free = Mock(return_value=1000000)
    gc.mem_alloc = Mock(return_value=2000000)

    # Optional convenience to improve speed.
    gc.collect = Mock() 
Example #11
Source File: umal.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def read(self):
        """ """
        import time
        return time.ticks_diff(time.ticks_ms(), self.start) / 1000.0 
Example #12
Source File: toolkit.py    From illuminOS with MIT License 5 votes vote down vote up
def timed_function(f, *args, **kwargs):
    import time
    myname = str(f).split(' ')[1]
    def new_func(*args, **kwargs):
        t = time.ticks_us()
        result = f(*args, **kwargs)
        delta = time.ticks_diff(t, time.ticks_us())
        log.debug('GC: {} Function {} Time = {:6.3f}ms'.format(str(gc.mem_free()), myname, delta/1000))
        return result

    return new_func

# @timed_function 
Example #13
Source File: hcsr04.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        if ticks_diff(ticks_ms(), self._last_measured) > self.INTERVAL:
            new_dist = self._measure()
            self._last_measured = ticks_ms()
            if abs(new_dist - self.distance) >= self.precision:
                self.distance = new_dist
        return self.distance 
Example #14
Source File: mpuserver.py    From py-mpu6050 with GNU General Public License v3.0 5 votes vote down vote up
def serve(self):
        print('starting mpu server on port {}'.format(self.port))

        lastgc = lastsent = lastread = time.ticks_ms()

        while True:
            now = time.ticks_ms()
            write_dt = time.ticks_diff(now, lastsent)
            read_dt = time.ticks_diff(now, lastread)
            gc_dt = time.ticks_diff(now, lastgc)

            time.sleep_ms(max(0, 1-read_dt))

            if self.flag_reset_gyro:
                self.mpu.filter.reset_gyro()
                self.flag_reset_gyro = False

            values = self.mpu.read_position()
            lastread = now

            if write_dt >= self.write_interval:
                lastsent = time.ticks_ms()
                self.sock.sendto(tojson(values), ('192.168.4.2', 8000))

            if gc_dt >= self.gc_interval:
                gc.collect() 
Example #15
Source File: mpuserver.py    From py-mpu6050 with GNU General Public License v3.0 5 votes vote down vote up
def isr(self, pin):
        # debounce
        if time.ticks_diff(time.ticks_ms(), self.last_isr) < 10:
            return

        print('! reset gyro request')
        self.flag_reset_gyro = True
        self.last_isr = time.ticks_ms() 
Example #16
Source File: unetrepl.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def flush(self):
        t = time.ticks_ms()
        if self.out_fill == 0:  # reset time, if there is nothing to send
            self.out_last_sent = t
            # debug dp.println("rt {}".format(t))
        elif time.ticks_diff(t, self.out_last_sent) > self.INTERVAL:
            # debug           dp.println("t {},{},{}".format(time.ticks_diff(t,self.out_last_sent),
            #                                           t,self.out_last_sent))
            self.acquire_out_buffer()
            self._send()
            self.release_out_buffer() 
Example #17
Source File: servo.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        if self.turn_start is not None:  # turn in process
            current = time.ticks_ms()
            if time.ticks_diff(current, self.turn_start) >= self.turn_time_ms:
                if len(self.angle_list) > 0:
                    self._trigger_next_turn()
                else:
                    self._release()
        return self.angle_list 
Example #18
Source File: hcsr04.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        if ticks_diff(ticks_ms(), self._last_measured) > self.INTERVAL:
            new_dist = self._measure()
            self._last_measured = ticks_ms()
            if abs(new_dist - self.distance) >= self.precision:
                self.distance = new_dist
        return self.distance 
Example #19
Source File: servo.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        if self.turn_start is not None:  # turn in process
            current = time.ticks_ms()
            if time.ticks_diff(current, self.turn_start) >= self.turn_time_ms:
                if len(self.angle_list) > 0:
                    self._trigger_next_turn()
                else:
                    self._release()
        return self.angle_list 
Example #20
Source File: mfrc522.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        now = time.ticks_ms()
        if time.ticks_diff(now, self.last_access) > self.access_interval:
            retval = b'0'  # Let's assume nothing is there
            try:
                (stat, tag_type) = self.request(_REQIDL)
                if stat == _OK:  # Something is there, so ignore this if not successfully read
                    retval = None

                    (stat, raw_uid) = self.anticoll()

                    if stat == _OK:
                        retval = str(tag_type).encode() + b' ' + ubinascii.hexlify(bytes(raw_uid))

                        if self.select_tag(raw_uid) == _OK:

                            data_read = False
                            for sector in range(0, self.datasize//12): # /16/3*4
                                if (sector+1) % 4 != 0:  # every 4th sector has only management info
                                    if self.auth(_AUTHENT1A, sector+4, self.key, raw_uid) == _OK:
                                        if not data_read:
                                            retval += b' '
                                        self._read(sector + 4, into=self.card_data_buf)
                                        retval += ubinascii.hexlify(self.card_data_buf)  # TODO: remove hexlify and do binary
                                        data_read = True
                                    else:
                                        print("MFRC522: authentication error")
                                        return None  # Not successfull read
                            self.stop_crypto1()
                            # TODO: think how to avoid this busy-waiting
                            print("MFRC522: read time " + str(time.ticks_diff(time.ticks_ms(), now)))
                        else:
                            print("MFRC522: Select failed")
                        _ = self.anticoll()  # prevent reading of empty
                        self.last_access = time.ticks_ms()  # TODO: check why this is necessary
            except Exception as e:
                print('Trouble in MFRC522. Got exception:', e)
                print('Retval so far:', retval)
            return retval
        return None  # didn't read 
Example #21
Source File: mfrc522.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        now = time.ticks_ms()
        if time.ticks_diff(now, self.last_access) > self.access_interval:
            retval = b'0'  # Let's assume nothing is there
            try:
                (stat, tag_type) = self.request(_REQIDL)
                if stat == _OK:  # Something is there, so ignore this if not successfully read
                    retval = None

                    (stat, raw_uid) = self.anticoll()

                    if stat == _OK:
                        retval = str(tag_type).encode() + b' ' + ubinascii.hexlify(bytes(raw_uid))

                        if self.select_tag(raw_uid) == _OK:

                            data_read = False
                            for sector in range(0, self.datasize//12): # /16/3*4
                                if (sector+1) % 4 != 0:  # every 4th sector has only management info
                                    if self.auth(_AUTHENT1A, sector+4, self.key, raw_uid) == _OK:
                                        if not data_read:
                                            retval += b' '
                                        self._read(sector + 4, into=self.card_data_buf)
                                        retval += ubinascii.hexlify(self.card_data_buf)  # TODO: remove hexlify and do binary
                                        data_read = True
                                    else:
                                        print("MFRC522: authentication error")
                                        return None  # Not successfull read
                            self.stop_crypto1()
                            # TODO: think how to avoid this busy-waiting
                            print("MFRC522: read time " + str(time.ticks_diff(time.ticks_ms(), now)))
                        else:
                            print("MFRC522: Select failed")
                        _ = self.anticoll()  # prevent reading of empty
                        self.last_access = time.ticks_ms()  # TODO: check why this is necessary
            except Exception as e:
                print('Trouble in MFRC522. Got exception:', e)
                print('Retval so far:', retval)
            return retval
        return None  # didn't read 
Example #22
Source File: i2c_connector.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        t = time.ticks_ms()
        # if self.suspend_start is not None \
        #        and time.ticks_diff(t,self.suspend_start) <= self.suspend_time:
        #    print("Bus access suspended.")
        if self.suspend_start is None \
                or time.ticks_diff(t, self.suspend_start) > self.suspend_time:
            self.suspend_start = None  # done waiting
            try:
                if self.msgq is not None:
                    self.port.writeto(self.addr, self.msgq)
                    self.msgq = None
                s = self.port.readfrom(self.addr, self.BUFFER_SIZE)
            except:
                print("Trouble accessing i2c.")
            else:
                if s[0] == 255 and s[1] == 255:  # illegal read
                    print("Got garbage, waiting 1s before accessing bus again.")
                    print("data:", s)
                    self.suspend_time = 1000  # take a break
                    self.suspend_start = time.ticks_ms();
                else:
                    count = s[0] * 256 + s[1]
                    if self.count != count:
                        l = s[2];
                        self.suspend_time = s[3];
                        # scale timer
                        if self.suspend_time & 128:
                            self.suspend_time = (self.suspend_time & 127) * 100
                            if self.suspend_time > 5000:  # should not happen
                                print("Garbage time -> waiting 1s before accessing bus again.")
                                print("data:", s)
                                self.suspend_time = 1000
                        if self.suspend_time > 0:
                            self.suspend_start = time.ticks_ms();
                            print("Bus suspend for", self.suspend_time, "ms requested.")
                        if l <= self.BUFFER_SIZE:  # discard if too big
                            self.count = count
                            self.current_value = s[4:4 + l]
                            return self.current_value
        return None 
Example #23
Source File: servo.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        if self.turn_start is not None:  # turn in process
            current = time.ticks_ms()
            if time.ticks_diff(current, self.turn_start) >= self.turn_time_ms:
                if len(self.angle_list) > 0:
                    self._trigger_next_turn()
                else:
                    self._release()
        return self.angle_list 
Example #24
Source File: hcsr04.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def _send_pulse_and_wait(self):
        # Send the pulse to trigger and listen on echo pin.
        # We use the method `machine.time_pulse_us()` to
        # get the microseconds until the echo is received.
        self.trigger_pin.value(0)  # Stabilize the sensor
        sleep_us(5)
        self.trigger_pin.on()
        # Send a 10us pulse.
        sleep_us(10)
        self.trigger_pin.off()
        # try:
        #     pulse_time = machine.time_pulse_us(self.echo_pin, 1, self.echo_timeout_us)
        #     return pulse_time
        # except OSError as ex:
        #     if ex.args[0] == 110: # 110 = ETIMEDOUT
        #         return -1 # out of range
        #     raise ex

        start = ticks_us()
        while not self.echo_pin():
            t = ticks_us()
            if ticks_diff(t, start) > self.echo_timeout_us:
                print("HCR04: timeout")
                return -1
        start = ticks_us()
        while self.echo_pin():
            t = ticks_us()
            if ticks_diff(t, start) > self.echo_timeout_us:
                print("HCR04: timeout")
                return -1
        delta = ticks_diff(ticks_us(), start)
        return delta 
Example #25
Source File: hcsr04.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        if ticks_diff(ticks_ms(), self._last_measured) > self.INTERVAL:
            new_dist = self._measure()
            self._last_measured = ticks_ms()
            if abs(new_dist - self.distance) >= self.precision:
                self.distance = new_dist
        return self.distance 
Example #26
Source File: i2c_connector.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        t = time.ticks_ms()
        # if self.suspend_start is not None \
        #        and time.ticks_diff(t,self.suspend_start) <= self.suspend_time:
        #    print("Bus access suspended.")
        if self.suspend_start is None \
                or time.ticks_diff(t, self.suspend_start) > self.suspend_time:
            self.suspend_start = None  # done waiting
            try:
                if self.msgq is not None:
                    self.port.writeto(self.addr, self.msgq)
                    self.msgq = None
                s = self.port.readfrom(self.addr, self.BUFFER_SIZE)
            except:
                print("Trouble accessing i2c.")
            else:
                if s[0] == 255 and s[1] == 255:  # illegal read
                    print("Got garbage, waiting 1s before accessing bus again.")
                    print("data:", s)
                    self.suspend_time = 1000  # take a break
                    self.suspend_start = time.ticks_ms();
                else:
                    count = s[0] * 256 + s[1]
                    if self.count != count:
                        l = s[2];
                        self.suspend_time = s[3];
                        # scale timer
                        if self.suspend_time & 128:
                            self.suspend_time = (self.suspend_time & 127) * 100
                            if self.suspend_time > 5000:  # should not happen
                                print("Garbage time -> waiting 1s before accessing bus again.")
                                print("data:", s)
                                self.suspend_time = 1000
                        if self.suspend_time > 0:
                            self.suspend_start = time.ticks_ms();
                            print("Bus suspend for", self.suspend_time, "ms requested.")
                        if l <= self.BUFFER_SIZE:  # discard if too big
                            self.count = count
                            self.current_value = s[4:4 + l]
                            return self.current_value
        return None 
Example #27
Source File: mfrc522.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        now = time.ticks_ms()
        if time.ticks_diff(now, self.last_access) > self.access_interval:
            retval = b'0'  # Let's assume nothing is there
            try:
                (stat, tag_type) = self.request(_REQIDL)
                if stat == _OK:  # Something is there, so ignore this if not successfully read
                    retval = None

                    (stat, raw_uid) = self.anticoll()

                    if stat == _OK:
                        retval = str(tag_type).encode() + b' ' + ubinascii.hexlify(bytes(raw_uid))

                        if self.select_tag(raw_uid) == _OK:

                            data_read = False
                            for sector in range(0, self.datasize//12): # /16/3*4
                                if (sector+1) % 4 != 0:  # every 4th sector has only management info
                                    if self.auth(_AUTHENT1A, sector+4, self.key, raw_uid) == _OK:
                                        if not data_read:
                                            retval += b' '
                                        self._read(sector + 4, into=self.card_data_buf)
                                        retval += ubinascii.hexlify(self.card_data_buf)  # TODO: remove hexlify and do binary
                                        data_read = True
                                    else:
                                        print("MFRC522: authentication error")
                                        return None  # Not successfull read
                            self.stop_crypto1()
                            # TODO: think how to avoid this busy-waiting
                            print("MFRC522: read time " + str(time.ticks_diff(time.ticks_ms(), now)))
                        else:
                            print("MFRC522: Select failed")
                        _ = self.anticoll()  # prevent reading of empty
                        self.last_access = time.ticks_ms()  # TODO: check why this is necessary
            except Exception as e:
                print('Trouble in MFRC522. Got exception:', e)
                print('Retval so far:', retval)
            return retval
        return None  # didn't read 
Example #28
Source File: hcsr04.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def _send_pulse_and_wait(self):
        # Send the pulse to trigger and listen on echo pin.
        # We use the method `machine.time_pulse_us()` to
        # get the microseconds until the echo is received.
        self.trigger_pin.value(0)  # Stabilize the sensor
        sleep_us(5)
        self.trigger_pin.on()
        # Send a 10us pulse.
        sleep_us(10)
        self.trigger_pin.off()
        # try:
        #     pulse_time = machine.time_pulse_us(self.echo_pin, 1, self.echo_timeout_us)
        #     return pulse_time
        # except OSError as ex:
        #     if ex.args[0] == 110: # 110 = ETIMEDOUT
        #         return -1 # out of range
        #     raise ex

        start = ticks_us()
        while not self.echo_pin():
            t = ticks_us()
            if ticks_diff(t, start) > self.echo_timeout_us:
                print("HCR04: timeout")
                return -1
        start = ticks_us()
        while self.echo_pin():
            t = ticks_us()
            if ticks_diff(t, start) > self.echo_timeout_us:
                print("HCR04: timeout")
                return -1
        delta = ticks_diff(ticks_us(), start)
        return delta 
Example #29
Source File: spimaster.py    From micropython-stm-lib with MIT License 5 votes vote down vote up
def timeit():
        spi = SpiMaster(1, baudrate=int(pyb.freq()[3] / 16))
        start = ticks_ms()

        for i in range(2 ** 10):
            spi.write_data(b'abcdefgh' * 4)
            spi.read_data()

        print("Millisecond ticks elapsed: %i" % ticks_diff(ticks_ms(), start)) 
Example #30
Source File: i2c_connector.py    From ulnoiot-upy with MIT License 5 votes vote down vote up
def measure(self):
        t = time.ticks_ms()
        # if self.suspend_start is not None \
        #        and time.ticks_diff(t,self.suspend_start) <= self.suspend_time:
        #    print("Bus access suspended.")
        if self.suspend_start is None \
                or time.ticks_diff(t, self.suspend_start) > self.suspend_time:
            self.suspend_start = None  # done waiting
            try:
                if self.msgq is not None:
                    self.port.writeto(self.addr, self.msgq)
                    self.msgq = None
                s = self.port.readfrom(self.addr, self.BUFFER_SIZE)
            except:
                print("Trouble accessing i2c.")
            else:
                if s[0] == 255 and s[1] == 255:  # illegal read
                    print("Got garbage, waiting 1s before accessing bus again.")
                    print("data:", s)
                    self.suspend_time = 1000  # take a break
                    self.suspend_start = time.ticks_ms();
                else:
                    count = s[0] * 256 + s[1]
                    if self.count != count:
                        l = s[2];
                        self.suspend_time = s[3];
                        # scale timer
                        if self.suspend_time & 128:
                            self.suspend_time = (self.suspend_time & 127) * 100
                            if self.suspend_time > 5000:  # should not happen
                                print("Garbage time -> waiting 1s before accessing bus again.")
                                print("data:", s)
                                self.suspend_time = 1000
                        if self.suspend_time > 0:
                            self.suspend_start = time.ticks_ms();
                            print("Bus suspend for", self.suspend_time, "ms requested.")
                        if l <= self.BUFFER_SIZE:  # discard if too big
                            self.count = count
                            self.current_value = s[4:4 + l]
                            return self.current_value
        return None