Exemplo n.º 1
0
 def _idle_thread(self):
     if self.gc_enable and (self.last_gc == 0 or after(self.last_gc) > GCTIME):
         gc.collect()
         self.last_gc = ticks_us()
     if self.heartbeat is not None and (self.last_heartbeat == 0 or after(self.last_heartbeat) > HBTIME):
         self.heartbeat.toggle()
         self.last_heartbeat = ticks_us()
Exemplo n.º 2
0
 async 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
Exemplo n.º 3
0
    def __init__(self, kp, ki, kd, dt, max_out, min_out, start_time = None):
        ''' Initializing

        Arguments:
            kp = proportional gain, float > 0
            kd = derivative gain, float >= 0
            ki = integral gain, float >=-
            dt = sample time (ms)
            max_out = the maximum output of the controller
            min_out = the minimum output of the controller
        '''
        print('Creating PID controller...')
        self.kp = kp
        self.kd = kd / dt
        self.ki = ki * dt
        self.dt = dt

        self.max_output = max_out
        self.min_output = min_out

        if start_time is None:
            self.current_time = utime.ticks_us()
            self.previous_time = self.current_time
        else:
            self.current_time = 0.0
            self.previous_time = 0.0

        self.last_Error = 0.0
        self.last_state = 0.0
        self.integral_term = 0.0

        self.output = 0.0
Exemplo n.º 4
0
    def _udp_thread(self):
        """
        UDP thread, reads data from the server and handles it.
        """

        while not self.udp_stop:
            try:
                data, src = self.sock.recvfrom(1024)
                _token = data[1:3]
                _type = data[3]
                if _type == PUSH_ACK:
                    self._log("Push ack")
                elif _type == PULL_ACK:
                    self._log("Pull ack")
                elif _type == PULL_RESP:
                    self.dwnb += 1
                    ack_error = TX_ERR_NONE
                    tx_pk = ujson.loads(data[4:])
                    tmst = tx_pk["txpk"]["tmst"]
                    t_us = tmst - utime.ticks_us() - 12500
                    if t_us < 0:
                        t_us += 0xFFFFFFFF
                    if t_us < 20000000:
                        self.uplink_alarm = Timer.Alarm(
                            handler=lambda x: self._send_down_link(
                                ubinascii.a2b_base64(tx_pk["txpk"]["data"]),
                                tx_pk["txpk"]["tmst"] - 50, tx_pk["txpk"]["datr"],
                                int(tx_pk["txpk"]["freq"] * 1000000)
                            ), 
                            us=t_us
                        )
                    else:
                        ack_error = TX_ERR_TOO_LATE
                        self._log('Downlink timestamp error!, t_us: {}', t_us)
                    self._ack_pull_rsp(_token, ack_error)
                    self._log("Pull rsp")
            except usocket.timeout:
                pass
            except OSError as ex:
                if ex.errno != errno.EAGAIN:
                    self._log('UDP recv OSError Exception: {}', ex)
            except Exception as ex:
                self._log('UDP recv Exception: {}', ex)

            # wait before trying to receive again
            utime.sleep_ms(UDP_THREAD_CYCLE_MS)

        # we are to close the socket
        self.sock.close()
        self.udp_stop = False
        self._log('UDP thread stopped')
def test(spi=3, cs='PB0'):
    print("SPI flash")
    cs = Pin(cs, Pin.OUT)
    spi = SPI(spi, baudrate=42000000, polarity=0, phase=0)
    flash = SPIFlash(spi, cs)

    print("Getting chip ID...")
    flash.wait()
    id_ = flash.getid()
    print("ID:", ubinascii.hexlify(id_))

    print("Reading block (32b) from address 0...")
    buf = bytearray(32)
    flash.read_block(0, buf)
    print(ubinascii.hexlify(buf))

    addr = 12 * 600 + 8
    print("Reading block (32b) from address {}...".format(addr))
    flash.read_block(addr, buf)
    print(ubinascii.hexlify(buf))

    addr = 524288
    print("Erasing 4k block at address {}...".format(addr))
    t1 = ticks_us()
    flash.erase(addr, '4k')
    # flash.erase(addr, '32k')
    # flash.erase(addr, '64k')
    # flash.erase_chip()
    t = ticks_diff(ticks_us(), t1)
    print("erase {} us".format(t))

    print("Writing blocks (256b) at address {}...".format(addr))
    buf = bytearray(range(256))
    t1 = ticks_us()
    flash.write_block(addr, buf)
    t = ticks_diff(ticks_us(), t1)
    mbs = len(buf) * 8. / t
    print("write({}) {} us, {} mbs".format(len(buf), t, mbs))

    print("Verifying write...")
    v = bytearray(256)
    flash.read_block(addr, v)
    if (v == buf):
        print("write/read ok")
    else:
        print("write/read FAILed")

    print("Timing 32k read from address 0...")
    gc.collect()
    buf = bytearray(32 * 1024)
    t1 = ticks_us()
    flash.read_block(0, buf)
    t = ticks_diff(ticks_us(), t1)
    mbs = len(buf) * 8. / t
    print("read({}) {} us, {} mbs".format(len(buf), t, mbs))
Exemplo n.º 6
0
    def compute_output(self, desired_state, current_state, current_time = None, previous_time = None):
        if current_time is None:
            # print('Current Time is None')
            self.current_time = utime.ticks_us()
        else:
            self.current_time = current_time

        if previous_time is not None:
            self.previous_time = previous_time

        # print('Current State: {}\t Desired State: {}'.format(current_state, desired_state))
        # print('Current Time: {}\t Previous Time: {}'.format(self.current_time, self.previous_time))

        if utime.ticks_diff(self.current_time, self.previous_time) >= self.dt:
            self.error = desired_state - current_state

#
# Correct for heading 'wrap around' to find shortest turn
#             if self.error > 180:
#                 self.error -= 360
#             elif self.error < -180:
#                 self.error += 360

            self.integral_term += self.ki * self.error

            self.state_change = current_state - self.last_state
            self.last_state = current_state

            # print('Error: {:}\t Error_dot: {:.4f}'.format(self.error, self.state_change))

            self.output = self.kp * self.error + self.integral_term - self.kd * self.state_change

            # limit the output to within the range of possible values
            if self.output > self.max_output:
                self.output = self.max_output
                # print('Limiting PID ouput to maximum')
            elif self.output < self.min_output:
                # print('Limiting PID output to minimum')
                self.output = self.min_output

            self.previous_time = self.current_time


        # print('PID output: {:}\n'.format(self.output))
        # print('{},{}\n'.format(current_state, self.output))

        return self.output
Exemplo n.º 7
0
    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
Exemplo n.º 8
0
    def _send_down_link(self, data, tmst, datarate, frequency):
        """
        Transmits a downlink message over LoRa.
        """

        self.lora.init(
            mode=LoRa.LORA,
            frequency=frequency,
            bandwidth=self._dr_to_bw(datarate),
            sf=self._dr_to_sf(datarate),
            preamble=8,
            coding_rate=LoRa.CODING_4_5,
            tx_iq=True
            )
        while utime.ticks_us() < tmst:
            pass
        self.lora_sock.send(data)
        self._log(
            'Sent downlink packet scheduled on {:.3f}, at {:.1f} Mhz using {}: {}',
            tmst / 1000000,
            self._freq_to_float(frequency),
            datarate,
            data
        )
Exemplo n.º 9
0
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))
Exemplo n.º 10
0
def microsWhen(timediff):                       # Expected value of counter in a given no. of uS
    if timediff >= MAXTIME:
        raise TimerException()
    return (ticks_us() + timediff) & TIMERPERIOD
Exemplo n.º 11
0
def microsUntil(tim):                           # uS from now until a specified time (used in Delay class)
    return ((tim - ticks_us()) & TIMERPERIOD)
Exemplo n.º 12
0
 def _cb_right():
     self.tright[self.iright & 15] = ticks_us()
     self.iright += 1
Exemplo n.º 13
0
def ping(host, count=4, timeout=5000, interval=10, quiet=False, size=64):
    import utime
    import uselect
    import uctypes
    import usocket
    import ustruct
    import urandom

    # prepare packet
    assert size >= 16, "pkt size too small"
    pkt = b'Q' * size
    pkt_desc = {
        "type": uctypes.UINT8 | 0,
        "code": uctypes.UINT8 | 1,
        "checksum": uctypes.UINT16 | 2,
        "id": uctypes.UINT16 | 4,
        "seq": uctypes.INT16 | 6,
        "timestamp": uctypes.UINT64 | 8,
    }  # packet header descriptor
    h = uctypes.struct(uctypes.addressof(pkt), pkt_desc, uctypes.BIG_ENDIAN)
    h.type = 8  # ICMP_ECHO_REQUEST
    h.code = 0
    h.checksum = 0
    h.id = urandom.getrandbits(16)
    h.seq = 1

    # init socket
    sock = usocket.socket(usocket.AF_INET, usocket.SOCK_RAW, 1)
    sock.setblocking(0)
    sock.settimeout(timeout / 1000)
    addr = usocket.getaddrinfo(host, 1)[0][-1][0]  # ip address
    sock.connect((addr, 1))
    not quiet and print("PING %s (%s): %u data bytes" % (host, addr, len(pkt)))

    seqs = list(range(1, count + 1))  # [1,2,...,count]
    c = 1
    t = 0
    n_trans = 0
    n_recv = 0
    finish = False
    while t < timeout:
        if t == interval and c <= count:
            # send packet
            h.checksum = 0
            h.seq = c
            h.timestamp = utime.ticks_us()
            h.checksum = checksum(pkt)
            if sock.send(pkt) == size:
                n_trans += 1
                t = 0  # reset timeout
            else:
                seqs.remove(c)
            c += 1

        # recv packet
        while 1:
            socks, _, _ = uselect.select([sock], [], [], 0)
            if socks:
                resp = socks[0].recv(4096)
                resp_mv = memoryview(resp)
                h2 = uctypes.struct(uctypes.addressof(resp_mv[20:]), pkt_desc,
                                    uctypes.BIG_ENDIAN)
                # TODO: validate checksum (optional)
                seq = h2.seq
                if h2.type == 0 and h2.id == h.id and (
                        seq in seqs):  # 0: ICMP_ECHO_REPLY
                    t_elasped = (utime.ticks_us() - h2.timestamp) / 1000
                    ttl = ustruct.unpack('!B', resp_mv[8:9])[0]  # time-to-live
                    n_recv += 1
                    not quiet and print(
                        "%u bytes from %s: icmp_seq=%u, ttl=%u, time=%f ms" %
                        (len(resp), addr, seq, ttl, t_elasped))
                    seqs.remove(seq)
                    if len(seqs) == 0:
                        finish = True
                        break
            else:
                break

        if finish:
            break

        utime.sleep_ms(1)
        t += 1

    # close
    sock.close()
    ret = (n_trans, n_recv)
    not quiet and print("%u packets transmitted, %u packets received" %
                        (n_trans, n_recv))
    return (n_trans, n_recv)
Exemplo n.º 14
0
def after(trigtime):                            # If current time is after the specified value return
    res = ((ticks_us() - trigtime) & TIMERPERIOD) # the no. of uS after. Otherwise return zero
    if res >= MAXTIME:
        res = 0
    return res
Exemplo n.º 15
0
def pulse(delay: int):
    while True:
        # normalize sin from interval -1:1 to 0:1
        yield 0.5 + 0.5 * math.sin(utime.ticks_us() / delay)
Exemplo n.º 16
0
 def new_func(*args, **kwargs):
     t = utime.ticks_us()
     result = f(*args, **kwargs)
     delta = utime.ticks_diff(t, utime.ticks_us())
     print('Function {} Time = {:6.3f}ms'.format(myname, delta/1000))
     return result
Exemplo n.º 17
0
def microsWhen(timediff):                       # Expected value of counter in a given no. of uS
    if timediff >= MAXTIME:
        raise TimerException()
    return (ticks_us() + timediff) & TIMERPERIOD
Exemplo n.º 18
0
    def __init__(self,
                 run_motor,
                 name='NoName',
                 priority=0,
                 period=None,
                 profile=False,
                 trace=False):
        """ Initializes a task object, saving copies of constructor parameters
        and preparing an empty dictionary for states. 
        @param run_fun The function which implements the task's code. It must
            be a generator which yields the current state
        @param name The name of the task, by default 'NoName.' This should
            @b really be overridden with a more descriptive name by the user
        @param priority The priority of the task, a positive integer with
            higher numbers meaning higher priority (default 0)
        @param period The time in milliseconds between runs of the task if 
            it's run by a timer or @c None if the task is not run by a timer.
            The time can be given in a @c float or @c int; it will be 
            converted to microseconds for internal use by the scheduler
        @param profile Set to @c True to enable run-time profiling 
        @param trace Set to @c True to generate a list of transitions between
            states. @b Note: This slows things down and allocates memory. """

        # The function which is run to implement this task's code. Since it
        # is a generator, we "run" it here, which doesn't actually run it but
        # gets it going as a generator which is ready to yield values

        #self._run_gen = run_fun ()
        self._run_gen = run_motor()

        ## The name of the task, hopefully a short and descriptive string.
        self.name = name

        ## The task's priority, an integer with higher numbers meaning higher
        #  priority.
        self.priority = int(priority)

        ## The period, in microseconds, between runs of the task's @c run()
        #  method. If the period is @c None, the @c run() method won't be run
        #  on a time basis but will instead be run by the scheduler as soon
        #  as feasible after code such as an interrupt handler calls the
        #  @c go() method.
        if period != None:
            self.period = int(period * 1000)
            self._next_run = utime.ticks_us() + self.period
        else:
            self.period = period
            self._next_run = None

        # Flag which causes the task to be profiled, in which the execution
        #  time of the @c run() method is measured and basic statistics kept.
        self._prof = profile
        self.reset_profile()

        # The previous state in which the task last ran. It is used to watch
        # for and track state transitions.
        self._prev_state = 0

        # If transition tracing has been enabled, create an empty list in
        # which to store transition (time, to-state) stamps
        self._trace = trace
        self._tr_data = []
        self._prev_time = utime.ticks_us()

        ## Flag which is set true when the task is ready to be run by the
        #  scheduler
        self.go_flag = False
Exemplo n.º 19
0
except OSError as e:
    restart_and_reconnect()

# Now that the client is connected lets get some info to send
adc = ADC(Pin(32))
adc.width(ADC.WIDTH_12BIT)
adc.atten(ADC.ATTN_11DB)

#---------------data part---------------#
message_interval = 50  #in miliseconds
sample_freq = 8000  #Hz
ticks_max = ticks_add(0, -1)
print("Time intil clock resets: ", ticks_max / 1e6 / 60, " minutes")
#---------------------------------------#

start_beggining = ticks_us()  #saves the start of the measurement
data = []


def publish(*args):
    global data
    global start_beggining

    data.append(ticks_diff(ticks_us(), start_beggining))
    client.publish(topic_pub, ujson.dumps(data))

    data = [ticks_us()]  #initiates a new data packet
    start_beggining = ticks_us()  #saves the new measurement beggining


tim = Timer(-1)
Exemplo n.º 20
0
# LED Control Example
#
# This example shows how to control your OpenMV Cam's built-in LEDs. Use your
# smart phone's camera to see the IR LEDs.

import time, utime, math, pyb

from pyb import Pin, ExtInt
from pyb import LED

red_led   = LED(1)

old = utime.ticks_us()
#old2 = utime.ticks_us()
#new = utime.ticks_ms()
#i = 0
diff = 1

sum = 0
count = 0

def callback(e):
    print(e)
    #global diff, old #, count
    #diff = utime.ticks_diff(old, utime.ticks_us())
    #if (diff > 13):
        #print(diff)
    #old = utime.ticks_us()
    ##count += 1
    ##red_led.on()
    ##utime.sleep_us(10)
Exemplo n.º 21
0
 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
Exemplo n.º 22
0
def microsUntil(tim):                           # uS from now until a specified time (used in Delay class)
    return ((tim - ticks_us()) & TIMERPERIOD)
Exemplo n.º 23
0
async def read_coro():
    imu.mag_trigger()
    await asyncio.sleep_ms(20)  # Plenty of time for mag to be ready
    f.write(ujson.dumps([imu.accel.xyz, imu.gyro.xyz, imu.mag_nonblocking.xyz, time.ticks_us()]))
    f.write('\n')
    return imu.accel.xyz, imu.gyro.xyz, imu.mag_nonblocking.xyz
Exemplo n.º 24
0
import sys
gc.collect()
print (gc.mem_free())
import network
import utime
from utime import sleep_ms,ticks_ms, ticks_us, ticks_diff
from machine import Pin, SPI, PWM, ADC
from math import sqrt
import ssd1306
from random import getrandbits, seed

# configure oled display SPI SSD1306
hspi = SPI(1, baudrate=8000000, polarity=0, phase=0)
#DC, RES, CS
display = ssd1306.SSD1306_SPI(128, 64, hspi, Pin(2), Pin(16), Pin(0))
seed(ticks_us())

#---buttons

btnU = const (1 << 1)
btnL = const (1 << 2)
btnR = const (1 << 3)
btnD = const (1 << 4)
btnA = const (1 << 5)
btnB = const (1 << 6)

Btns = 0
lastBtns = 0

pinBtn = Pin(5, Pin.OUT)
pinPaddle = Pin(4, Pin.OUT)
Exemplo n.º 25
0
def main():
    """Initialize display."""

    if sys.platform == 'esp8266':
        print('1.4 inch TFT screen test on ESP8266')
        SPI_CS = 16
        SPI_DC = 15
        spi = SPI(1)

    elif sys.platform == 'esp32':
        print('1.4 inch TFT screen test on ESP32')
        sck = Pin(18)
        miso = Pin(19)
        mosi = Pin(23)
        SPI_CS = 26
        SPI_DC = 5

    # Baud rate of 14500000 seems about the max
    spi = SPI(2, baudrate=32000000, sck=sck, mosi=mosi, miso=miso)
    display = Display(spi, SPI_CS, SPI_DC)
    #    spi = SPI(2, baudrate=14500000, sck=Pin(18), mosi=Pin(23))

    # Draw background image
    display.draw_image('images/Arkanoid_Border128x118.raw', 0, 10, 128, 118)

    # Initialize ADC on VP pin 36
    adc = ADC(Pin(36))
    # Set attenuation 0-3.3V
    adc.atten(ADC.ATTN_11DB)

    # Seed random numbers
    seed(ticks_us())

    # Generate bricks
    MAX_LEVEL = const(9)
    level = 1
    bricks = load_level(level, display)

    # Initialize paddle
    paddle = Paddle(display)

    # Initialize score
    score = Score(display)

    # Initialize balls
    balls = []
    # Add first ball
    balls.append(Ball(59, 111, -2, -1, display, frozen=True))

    # Initialize lives
    lives = []
    for i in range(1, 3):
        lives.append(Life(i, display))

    # Initialize power-ups
    powerups = []

    try:
        while True:
            timer = ticks_us()
            # Set paddle position to ADC spinner (scale 6 - 98)
            paddle.h_position((4096 - adc.read()) // 44 + 5)
            # Handle balls
            score_points = 0
            for ball in balls:
                # Position
                ball.set_position(paddle.x, paddle.y, paddle.x2, paddle.center)

                # Check for collision with bricks if not frozen
                if not ball.frozen:
                    prior_collision = False
                    ball_x = ball.x
                    ball_y = ball.y
                    ball_x2 = ball.x2
                    ball_y2 = ball.y2
                    ball_center_x = ball.x + ((ball.x2 + 1 - ball.x) // 2)
                    ball_center_y = ball.y + ((ball.y2 + 1 - ball.y) // 2)
                    # Check for hits
                    for brick in bricks:
                        if (ball_x2 >= brick.x and ball_x <= brick.x2
                                and ball_y2 >= brick.y and ball_y <= brick.y2):
                            # Hit
                            if not prior_collision:
                                ball.x_speed, ball.y_speed = brick.bounce(
                                    ball.x, ball.y, ball.x2, ball.y2,
                                    ball.x_speed, ball.y_speed, ball_center_x,
                                    ball_center_y)
                                prior_collision = True
                            score_points += 1
                            brick.clear()
                            bricks.remove(brick)

                    # Generate random power-ups
                    if score_points > 0 and randint(1, 20) == 7:
                        powerups.append(Powerup(ball.x, 64, display))

                # Check for missed
                if ball.y2 > display.height - 3:
                    ball.clear_previous()
                    balls.remove(ball)
                    if not balls:
                        # Clear powerups
                        powerups.clear()
                        # Lose life if last ball on screen
                        if len(lives) == 0:
                            score.game_over()
                        else:
                            # Subtract Life
                            lives.pop().clear()
                            # Add ball
                            balls.append(
                                Ball(59, 112, 2, -3, display, frozen=True))
                else:
                    # Draw ball
                    ball.draw()
            # Update score if changed
            if score_points:
                score.increment(score_points)
            # Handle power-ups
            for powerup in powerups:
                powerup.set_position(paddle.x, paddle.y, paddle.x2,
                                     paddle.center)
                powerup.draw()
                if powerup.collected:
                    # Power-up collected
                    powerup.clear()
                    # Add ball
                    balls.append(
                        Ball(powerup.x, 112, 2, -1, display, frozen=False))
                    powerups.remove(powerup)
                elif powerup.y2 > display.height - 3:
                    # Power-up missed
                    powerup.clear()
                    powerups.remove(powerup)

            # Check for level completion
            if not bricks:
                for ball in balls:
                    ball.clear()
                balls.clear()
                for powerup in powerups:
                    powerup.clear()
                powerups.clear()
                level += 1
                if level > MAX_LEVEL:
                    level = 1
                bricks = load_level(level, display)
                balls.append(Ball(59, 111, -2, -1, display, frozen=True))
            # 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()
Exemplo n.º 26
0
 def y_callback(self, line):
     self.forward = self.pin_x.value() ^ self.pin_y.value() ^ self.reverse ^ 1
     self._pos += 1 if self.forward else -1
     self.tprev = self.tlast
     self.tlast = utime.ticks_us()
Exemplo n.º 27
0
    async def show(self):
        while True:
            print('show: state={}'.format(self.state))
            if self.state == self.ENTER_PIN1:
                self.pin1[self.round] = await ux_enter_pin(
                    title='Security Code',
                    heading='{} Security Code'.format('Old' if self.round ==
                                                      0 else 'New'))
                if self.pin1[self.round] != None and len(
                        self.pin1[self.round]) >= MIN_PIN_PART_LEN:
                    if self.round == 1:
                        self.goto(self.SHOW_ANTI_PHISHING_WORDS)
                    else:
                        self.goto(self.ENTER_PIN2)

            elif self.state == self.SHOW_ANTI_PHISHING_WORDS:
                start = utime.ticks_us()
                words = pincodes.PinAttempt.anti_phishing_words(
                    self.pin1[self.round].encode())
                end = utime.ticks_us()
                result = await ux_show_word_list('Security Words',
                                                 words,
                                                 heading1='Remember these',
                                                 heading2='Security Words:',
                                                 left_btn='BACK',
                                                 right_btn='OK')
                if result == 'x':
                    self.pin1[self.round] = None
                    self.goto(self.ENTER_PIN1)
                else:
                    self.goto(self.ENTER_PIN2)

            elif self.state == self.ENTER_PIN2:
                self.pin2[self.round] = await ux_enter_pin(
                    title='Login PIN',
                    heading='{} Login PIN'.format('Old' if self.round ==
                                                  0 else 'New'))
                if self.pin2[self.round] != None and len(
                        self.pin2[self.round]) >= MIN_PIN_PART_LEN:
                    if self.round == 0:
                        self.round = 1
                        self.goto(self.ENTER_PIN1)
                    else:
                        self.goto(self.CHANGE_PIN)

            elif self.state == self.CHANGE_PIN:
                try:
                    print('pin1={} pin2={}'.format(self.pin1, self.pin2))
                    args = {}
                    args['old_pin'] = (self.pin1[0] + self.pin2[0]).encode()
                    args['new_pin'] = (self.pin1[1] + self.pin2[1]).encode()
                    print('pa.change: args={}'.format(args))
                    pa.change(**args)
                    self.goto(self.CHANGE_SUCCESS)
                except Exception as err:
                    print('err={}'.format(err))
                    self.goto(self.CHANGE_FAILED)

            elif self.state == self.CHANGE_FAILED:
                result = await ux_show_story(
                    'Unable to change PIN.  The old PIN you entered was incorrect.',
                    title='PIN Error',
                    right_btn='RETRY')
                if result == 'y':
                    self.pin1 = [None, None]
                    self.pin2 = [None, None]
                    self.round = 0
                    self.goto(self.ENTER_PIN1)
                else:
                    return

            elif self.state == self.CHANGE_SUCCESS:
                dis.fullscreen('PIN changed')
                utime.sleep(1)
                return

            else:
                while True:
                    print('ERROR: Should never hit this else case!')
                    from uasyncio import sleep_ms
                    await sleep_ms(1000)
Exemplo n.º 28
0
def timeout_ns(nanoseconds):
    start = utime.ticks_us()

    while True:
        yield ((utime.ticks_us() - start) * 1000) >= nanoseconds
from machine import Pin
import utime

ir_pin = Pin(21, Pin.IN)
prev_value = 1
data = []

while True:
    ir_value = ir_pin.value()


    if ir_value == 0 and prev_value == 1:
        zero_start = utime.ticks_us()
        one_timed = utime.ticks_diff(utime.ticks_us(),one_start)
        #print(data)
        if one_timed < 50000:
            data.append((1, one_timed))
        
    if ir_value == 1 and prev_value == 0:
        one_start = utime.ticks_us()
        zero_timed = utime.ticks_diff(utime.ticks_us(),zero_start)

        if zero_timed < 50000:
            data.append((0, zero_timed))
        if one_timed > 100000 and len(data)>5:
            print(data, "\n", "Last one timed was", one_timed, "\n")
            data = []
            one_timed = utime.ticks_diff(utime.ticks_us(),one_start)

    prev_value = ir_value
#sw = pyb.Switch()

# Choose test to run
Calibrate = True
Timing = True

def getmag():                               # Return (x, y, z) tuple (blocking read)
    return imu.mag.xyz

if Calibrate:
    print("Calibrating. Press switch when done.")
    fuse.calibrate(getmag, sw, lambda : pyb.delay(100))
    print(fuse.magbias)

if Timing:
    mag = imu.mag.xyz # Don't include blocking read in time
    accel = imu.accel.xyz # or i2c
    gyro = imu.gyro.xyz
    start = time.ticks_us()  # Measure computation time only
    fuse.update(accel, gyro, mag) # 1.97mS on Pyboard
    t = time.ticks_diff(time.ticks_us(), start)
    print("Update time (uS):", t)

count = 0
while True:
    fuse.update(imu.accel.xyz, imu.gyro.xyz, imu.mag.xyz) # Note blocking mag read
    if count % 50 == 0:
        print("Heading, Pitch, Roll: {:7.3f} {:7.3f} {:7.3f}".format(fuse.heading, fuse.pitch, fuse.roll))
    time.sleep_ms(20)
    count += 1
Exemplo n.º 31
0
 def _cb_left():
     self.tleft[self.ileft & 15] = ticks_us()
     self.ileft += 1
Exemplo n.º 32
0
        leds(2,5)
    else:
        leds(2,0)


init()

cur_num_tx = 0
ur=""
wait_start()
tp = 1 #test_period s
t_tick = int(tp * 1000000)

rt=0.5
send_tick = int(t_tick/rt)
t_l = ut.ticks_us()
cidx=0
lc = 1


while True:
    rxc = 0
    txc = 0
    t_s = ut.ticks_us()
    lu = len(uids)
    #broadcast device exist every test period
    txp(0,2,lu)#compass.heading()
    mt()
    show_id()
    leds_br()
Exemplo n.º 33
0
 def y_callback(self, line):
     self.forward = self.pin_x.value() ^ self.pin_y.value() ^ 1
     self._pos += 1 if self.forward else -1
     self.tprev = self.tlast
     self.tlast = utime.ticks_us()
Exemplo n.º 34
0
def read_IMU_data():
    global ax, ay, az, angx, angy, angz, buff, index, good_data, new_chunk, serial
    #    timeout = 0.0001
    #    time_now = time.clock()
    #    while ((time.clock() - time_now) < timeout and not good_data):
    timeout = ut.ticks_add(ut.ticks_us(), 800)

    while (ut.ticks_diff(timeout, ut.ticks_us())) > 0 and (not good_data):
        #    while (not good_data):
        if serial.any():
            read_char = serial.read(1)
            #print(read_char)
        else:
            return

        if not new_chunk:
            # We are waiting for header byte
            if read_char == b'\x55':
                new_chunk = True
                buff[index] = ord(read_char)
                # print(buff[index])
                index += 1
                continue

        else:
            buff[index] = ord(read_char)
            # print(ord(read_char))
            index += 1

            if index >= 11:
                # reset & set OK to process flag
                index = 0
                new_chunk = False
                checksum = sum(buff[0:10])

                if checksum.to_bytes(2, 'big')[1] == buff[10]:
                    # Good data
                    good_data = True

    if good_data == True:
        good_data = False
        if buff[1] == b'\x50':
            # Time, not implemented
            pass
        elif buff[1] == 81:
            g = 9.81
            conv = 16.0 / 32768.0
            accel = struct.unpack("<hhh", buff[2:8])
            ax, ay, az = [a * conv for a in accel]
#            print('Acceleration', "ax: ", "{0:.2f}".format(ax), "ay: ", "{0:.2f}".format(ay), "az: ", "{0:.2f}".format(az))
#            temp = struct.unpack("<h", buff[8:10])
#            temp = temp[0] / 100.0
#            print("Temp: ", temp)
        elif buff[1] == 82:
            conv = 2000.0 / 32768.0
            angles = struct.unpack("<hhh", buff[2:8])
            angvx, angvy, angvz = [a * conv for a in angles]
#            print("Ang V", "angVx: ", "{0:.2f}".format(angvx), "angVy: ", "{0:.2f}".format(angvy), "angVz: ", "{0:.2f}".format(angvz))

        elif buff[1] == 83:
            conv = 180.0 / 32768.0
            angles = struct.unpack("<hhh", buff[2:8])
            angx, angy, angz = [a * conv for a in angles]
#            print("Angles", "angx: ", "{0:.2f}".format(angx), "angy: ", "{0:.2f}".format(angy), "angz: ", "{0:.2f}".format(angz))
        elif buff[1] == 84:
            conv = 1
            mag = struct.unpack("<hhh", buff[2:8])
            magx, magy, magz = [a * conv for a in mag]
#            print("Magnetic", "magx: ", "{0:.2f}".format(magx), "magy: ", "{0:.2f}".format(magy), "magz: ", "{0:.2f}".format(magz))

        return True

    else:
        return False
Exemplo n.º 35
0
    def bi_transfer(self):
        cur_num_tx = 0
        self.wait_start()

        test_cnt = 0

        while True:
            self.rx_cnt = 0
            self.rx_new_cnt = 0
            self.tx_cnt = 0
            self.tx_new_cnt = 0
            self.ack_cnt = 0
            test_period = 1  #s
            test_tick = int(test_period * 1000000)
            test_cnt += 1
            time_s = utime.ticks_us()
            time_l = time_s

            #broadcast device exist every test period
            self.tx(0, str(0))
            # rate target hz
            rate_target = random.randint(1, 100)
            send_tick = int(test_tick / rate_target)

            while True:  # start current measurement
                time_now = utime.ticks_us()
                time_use = utime.ticks_diff(time_now, time_s)
                if test_tick - time_use < 0:  # 10s
                    self.used_ids = self.used_ids_next
                    self.show_id()
                    self.used_ids_next = []
                    break

                time_last = utime.ticks_diff(time_now, time_l)
                if send_tick - time_last < 0:  # should send
                    time_l = time_now
                    if self.ack_received:
                        cur_num_tx = cur_num_tx + 1
                    self.ack_received = False
                    if len(self.used_ids) > 0:
                        index = random.randint(0, len(self.used_ids) - 1)
                        did = self.used_ids[index]
                        self.tx(did, cur_num_tx)
                        self.tx_new_cnt += 1

                incoming = radio.receive()
                if incoming:
                    self.rx_cnt += 1
                    items = incoming.split(":")
                    if len(items) == 3:

                        sid, did, value = items
                        sid = int(sid)
                        did = int(did)
                        if not sid in self.used_ids:
                            self.used_ids.append(sid)
                            self.show_id()

                        if not sid in self.used_ids_next:
                            self.used_ids_next.append(sid)

                        if sid == self.sid:  # sid collision
                            self.sid = self.get_new_id(self.used_ids)
                            self.show_id()

                        if did == self.sid:
                            if value == self.ack:
                                self.ack_received = True
                                self.ack_cnt += 1
                            else:
                                self.rx_new_cnt += 1
                                self.tx(sid, self.ack)
                            #radio.send ("%i:%i:%s"%(self.sid,sid,self.ack))

                    self.pixel_debug(0, self.rx_cnt)
                if button_b.was_pressed():  # test sid collision
                    if len(self.used_ids) > 0:
                        self.sid = self.used_ids[0]
                    else:
                        self.sid = random.randint(1, 20)
                    break
            tx_rate = float(self.tx_new_cnt) / test_period
            rx_rate = float(self.rx_new_cnt) / test_period
            str_output = "(%.1f,%.1f,%i)" % (tx_rate, rx_rate,
                                             self.tx_new_cnt - self.ack_cnt)

            print(str_output)
 def new_func(*args, **kwargs):
     t = utime.ticks_us()
     result = f(*args, **kwargs)
     delta = utime.ticks_diff(utime.ticks_us(), t)
     print('Function {} Time = {:6.3f}ms'.format(myname, delta / 1000))
     return result
Exemplo n.º 37
0
def after(trigtime):                            # If current time is after the specified value return
    res = ((ticks_us() - trigtime) & TIMERPERIOD) # the no. of uS after. Otherwise return zero
    if res >= MAXTIME:
        res = 0
    return res
Exemplo n.º 38
0
def pulse(delay: int) -> float:
    # normalize sin from interval -1:1 to 0:1
    return 0.5 + 0.5 * math.sin(utime.ticks_us() / delay)
Exemplo n.º 39
0
def toggle(_):
    global t
    pinout.value(not pinout.value())
    t = utime.ticks_us()
Exemplo n.º 40
0
 def _idle_thread(self):                     # Runs once then in roundrobin or when there's nothing else to do
     if self.gc_enable and (self.last_gc == 0 or after(self.last_gc) > GCTIME):
         gc.collect()
         self.last_gc = ticks_us()
Exemplo n.º 41
0
 def handle(self, task: Task) -> None:
     deadline = utime.ticks_add(utime.ticks_us(), self.delay_us)
     schedule(task, deadline, deadline)
Exemplo n.º 42
0
print('Battery Voltage=' + '{:.2f}'.format(voltage) + 'V')

# Ping a node
tof = nm3.send_ping(170)
distance = tof*SOUND_SPEED
print('Time of Flight to ' '{:03d}'.format(addr) + ' = ' + '{:.4f}'.format(tof) + 's' + ' distance = ' + '{:.4f}'.format(distance) + 'm')

# Need a pause between transmissions for the modem to finish the last one
utime.sleep(1.0)

# Configure I/O pin "Y3" as an external interrupt connected to RxS pin of Nanomodem
# Rising Edge on RxS pin indicate start of incoming packet on Nanomodem.
extint = pyb.ExtInt('Y3', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, rxs_callback)

# Global Variable
previous_arrival_tick = utime.ticks_us()

# Receiving unicast and broadcast messages
while True:
    # print("Arrival Flag: ", arrival_bflag)
    # Poll the serial port for bytes if interrupt happen
    if arrival_bflag:
        # Set flag to False for next interrupt to set it True
        arrival_bflag = False

        # Poll UART for data
        nm3.poll_receiver()

        # Periodically process any bytes received
        nm3.process_incoming_buffer()
Exemplo n.º 43
0
def GUIInputbox(obj):
    if obj.Status == 0:
        x = obj.X
        y = obj.Y
        width = obj.Width
        color = 0xcccccc
    elif obj.Status == 1:
        x = obj.X
        y = obj.Y
        width = obj.Width
        color = 0x33ccff
    else:
        lcd.fill(0x000000)
        x = 10
        y = 35
        width = 300
        color = 0x33ccff
    lcd.font(lcd.FONT_Ubuntu)
    lcd.print(obj.Label, x, y, color)
    lcd.font(lcd.FONT_Default)
    lcd.line(x, y + 40, x + width, y + 40, color)
    cw = 10
    ch = 16
    s = obj.TextValue
    mx = int(width / cw)
    st = s[-mx:]
    stl = len(st)
    xp = len(s) - stl
    for i in range(stl):
        lcd.print(st[i], x + i * cw, y + 20, 0xffffff)
    if obj.Status == 2:
        kc = 0
        caps = 0
        cs = 0
        cp = len(s[xp:]) if len(s[xp:]) < mx else mx
        while True:
            k, kc, caps = GUIKeyboard(kc, caps)
            if k != '':
                if len(k) == 1:
                    lcd.line(x + cp * cw, y + 20 - 4, x + cp * cw, y + 20 + ch,
                             0x000000)
                    s = s[0:xp + cp] + str(k) + s[xp + cp:]
                    k = 'right'
                if k == 'backspace':
                    if cp > 0:
                        s = s[0:xp + cp - 1] + s[xp + cp:]
                        k = 'left'
                if k == 'esc':
                    lcd.clear()
                    obj.Status = 1
                    break
                if k == 'enter':
                    lcd.clear()
                    obj.Status = 1
                    obj.TextValue = s
                    if obj.Function != None:
                        obj.Function(obj)
                    break
                if k == 'left':
                    lcd.line(x + cp * cw, y + 20 - 4, x + cp * cw, y + 20 + ch,
                             0x000000)
                    if cp - 1 > 0:
                        cp = cp - 1
                    else:
                        xp = xp - 1 if xp - 1 >= 0 else xp
                if k == 'right':
                    lcd.line(x + cp * cw, y + 20 - 4, x + cp * cw, y + 20 + ch,
                             0x000000)
                    if cp + 1 <= len(s[xp:xp + mx]):
                        cp = cp + 1
                    else:
                        xp = xp + 1 if xp + 1 + cp <= len(s) else xp
                for i in range(mx):
                    lcd.print('W', x + i * cw, y + 20, 0x000000)
                st = s[xp:xp + mx]
                stl = len(st)
                for i in range(stl):
                    lcd.print(st[i], x + i * cw, y + 20, 0xffffff)
            else:
                if time.ticks_us() - obj.Time >= 500000:
                    obj.Time = time.ticks_us()
                    if cs == 0:
                        lcd.line(x + cp * cw, y + 20 - 4, x + cp * cw,
                                 y + 20 + ch, 0xffffff)
                        cs = 1
                    else:
                        lcd.line(x + cp * cw, y + 20 - 4, x + cp * cw,
                                 y + 20 + ch, 0x000000)
                        cs = 0
    return obj
Exemplo n.º 44
0
def rxs_callback(line):
    global current_arrival_tick, arrival_bflag
    current_arrival_tick = utime.ticks_us()
    arrival_bflag = True
Exemplo n.º 45
0
tft.draw_hline(x, y, 50, GREEN)
tft.draw_vline(x, y, 50, GREEN)
tft.draw_hline(x, y + 50, 50, GREEN)
tft.draw_vline(x + 50, y, 50, GREEN)
tft.draw_line(x, y, x + 50, y + 50, GREEN)
tft.draw_line(x, y + 50, x + 50, y, GREEN)

# Render a glyph and measure performance.
xstart = 100
y = 80
tft.draw_str('Measure render speed of Python font:', xstart, y, GREEN, BLACK)
y += 20
mv, rows, cols = font10.get_ch('A')
nchars = 30
x = xstart
t = ticks_us()
for _ in range(nchars):
    tft.draw_glyph(mv, x, y, rows, cols, GREEN, BLACK)
    x += cols
y += rows
x = xstart
dt = ticks_diff(ticks_us(), t) / (nchars * 1000)
tft.draw_str('Time per char: {:4.1f}ms'.format(dt), xstart, y, GREEN, BLACK)

# Verify glyph doesn't exceed bounding box
x, y = 400, 10
tft.fill_rectangle(x, y, x + 40, y + 40, GREEN)
x = 388
tft.draw_glyph(mv, x, y, rows, cols, BLACK, YELLOW)

# Test pixel draw
Exemplo n.º 46
0
from machine import UART
import machine
import os
from network import WLAN
from network import Bluetooth
from network import LTE
from pytrack import Pytrack
import network
import utime
import pycom

start = utime.ticks_us()
uart = UART(0, baudrate=115200)
os.dupterm(uart)

# switch stuff off ...
# WLAN off
wlan = WLAN()
#wlan.init(mode=WLAN.STA)
wlan.deinit()
# Bluetooth off
#bt = Bluetooth()
#bt.deinit()
# LTE off
#lte = LTE()
#lte.disconnect()
#lte.deinit()
# switch off FTP and telnet servers
server = network.Server()
server.deinit()
# done switching stuff off
Exemplo n.º 47
0
import utime
try:
    utime.sleep_ms
except AttributeError:
    print("SKIP")
    raise SystemExit

utime.sleep_ms(1)
utime.sleep_us(1)
print(utime.ticks_diff(utime.ticks_ms(), utime.ticks_ms()) <= 1)
print(utime.ticks_diff(utime.ticks_us(), utime.ticks_us()) <= 500)
Exemplo n.º 48
0
 def new_func(*args, **kwargs):
     t = utime.ticks_us()
     result = f(*args, **kwargs)
     delta = utime.ticks_diff(utime.ticks_us(), t)  # Argument order new, old
     print('Function {} Time = {:6.3f}ms'.format(myname, delta/1000))
     return result