コード例 #1
0
ファイル: main.py プロジェクト: alexeckermann/esp32-lamp
def tick(timer):
    global neue, animation, animation_index

    # t_start = time.ticks_us()
    frame = animation[animation_index]
    # t_frame = time.ticks_us()

    # if animation_index == 0:
    # 	print('frame[0]: {}'.format(t_frame - t_start))
    # print('[{}] {}'.format(animation_index, frame))

    t_start = time.ticks_us()
    for pixel in range(len(frame)):
        neue[pixel] = frame[pixel]
    t_d_set = time.ticks_us() - t_start

    neue.write()
    t_d_write = time.ticks_us() - t_start

    if animation_index == 0:
        print('neue[0]: set {} - write {}'.format(t_d_set, t_d_write))

    gc.collect()

    if animation_index < (animation.frame_count - 1):
        animation_index += 1
    else:
        animation_index = 0
コード例 #2
0
def time_oh(f, n):
    t0 = time.ticks_us()
    f(n)
    t1 = time.ticks_us()
    dt = time.ticks_diff(t1, t0)
    fmt = 'time.ticks_us() oh : {:f} usec'
    print(fmt.format(dt))
コード例 #3
0
ファイル: test_amg8833.py プロジェクト: snakeuschi/robotling
    def find_some_blobs(n):
        # Liest `n` Bilder ein und versucht Blobs zu finden. Dazu wird die
        # Funktion `find_blobs` aus dem Modul `blob` benutzt; `find_blobs` läuft
        # auf dem Mikrokontroller. Die gefundenen Blobs und die mittlere Lauf-
        # zeit von `find_blobs` werden ausgegeben.
        delta = 0
        for i in range(n):
            # Bild einlesen
            img = list(amg.pixels_64x1)

            # Blobs suchen
            # `find_blobs` liefert eine Liste, in der jeder Eintrag aus einer Liste
            # von Parametern besteht, die einen Blob beschreiben:
            # [ID, area, x, x, prob], wobei `ID` der Index des Blobs ist, `area` die
            # Größe, `x`,`y` die Position und `prob` eine Abschätzung, wie sicher
            # die Funktion ist, dass dies ein Blob ist.
            t = ticks_us()
            res = blob.find_blobs(img, (8, 8))
            delta += ticks_diff(ticks_us(), t)

            # Blobs anzeigen, falls welche gefunden wurden
            s = ""
            for b in res:
                if b[1] > 1:
                    s += "{0:.0f}-pixel blob at {1:.1f},{2:.1f} ".format(
                        b[1], b[2], b[3])
            if len(s) > 0:
                print("{0:2.0d}: {1}".format(i, s))

            # Kurz warten
            sleep_ms(200)

        # Mittlere Dauer eines `find_blobs`-Aufrufs ausgeben
        print('{:6.3f}ms per call (average)\n'.format(delta / (n * 1000)))
コード例 #4
0
ファイル: adcBenchmark.py プロジェクト: wwkkww1983/ADCOverUDP
def testSoundLength():
    read_value = getADCtrigger(floor)
    start = time.ticks_us()
    _ = adc.readMeaningfulValue()
    duration = time.ticks_diff(time.ticks_us(), start)
    print("signal length : %i useconds" % duration)
    print("\t(%i samples)" % i)
コード例 #5
0
def time_it(f, n):
    t0 = time.ticks_us()
    f(n)
    t1 = time.ticks_us()
    dt = time.ticks_diff(t1, t0)
    fmt = "{:5.3f} sec, {:6.3f} usec/solve, {:8.4f} solves/sec"
    print(fmt.format(dt * 1e-6, dt / n, n / dt * 1e3))
コード例 #6
0
ファイル: utils.py プロジェクト: electromantis79/WHHC
def send_events(sock, json_string, mode, print_flag=False):
    need_acknowledgement_flag = False
    if json_string:
        # Send some data to remote server
        # Connect to remote server
        tic = time.ticks_us() / 1000
        # print('Send START', tic, 'ms')

        try:
            # Send the whole string
            sock.sendall(json_string)
            toc = time.ticks_us() / 1000
            need_acknowledgement_flag = True
            if print_flag:
                print('\n        Send END', toc, 'ms, Dif send', toc - tic,
                      'ms:', json_string)

        except OSError as err:
            if err.errno == 104:  # ECONNRESET
                print("        send_button_events OS error ECONNRESET:", err)
            else:
                print("        send_button_events OS error:", err)
            need_acknowledgement_flag = False

            mode = 'SearchModes'
            print('\n======== END Connected Modes ========\n')
            print('\n======== BEGIN Search Modes ========\n')

    return need_acknowledgement_flag, sock, mode
コード例 #7
0
    def setup():
        senMPU()
        global ori
        ori = Fusion()

        Timing = True
        Calibrate = False

        def getmag():
            senMPU()
            return mag

        if Calibrate:
            print("Calibrant. Presionar KEY un cop acabat.")
            ori.calibrate(getmag, sw, lambda: pyb.delay(100))
            print(ori.magbias)

        if Timing:
            '''
            mag = mpu.magnetic # Don't include blocking read in time
            accel = mpu.acceleration # or i2c
            gyro = mpu.gyro
            '''
            senMPU()
            start = time.ticks_us()  # Measure computation time only
            ori.update(accel, gyro, mag, 0.005)  # 1.97mS on Pyboard
            t = time.ticks_diff(time.ticks_us(), start)
            print("Temps de mostreig (uS):", t)
コード例 #8
0
 def _get_spad_info(self):
     # Get reference SPAD count and type, returned as a 2-tuple of
     # count and boolean is_aperture.  Based on code from:
     #   https://github.com/pololu/vl53l0x-arduino/blob/master/VL53L0X.cpp
     self._write_u8(0x80, 0x01)
     self._write_u8(0xFF, 0x01)
     self._write_u8(0x00, 0x00)
     self._write_u8(0xFF, 0x06)
     self._write_u8(0x83, self._read_u8(0x83) | 0x04)
     self._write_u8(0xFF, 0x07)
     self._write_u8(0x81, 0x01)
     self._write_u8(0x80, 0x01)
     self._write_u8(0x94, 0x6b)
     self._write_u8(0x83, 0x00)
     start = time.ticks_us()
     while self._read_u8(0x83) == 0x00:
         if self.io_timeout_s > 0 and \
            (time.ticks_us() - start) >= self.io_timeout_s:
             raise RuntimeError('Timeout waiting for VL53L0X!')
     self._write_u8(0x83, 0x01)
     tmp = self._read_u8(0x92)
     count = tmp & 0x7F
     is_aperture = ((tmp >> 7) & 0x01) == 1
     self._write_u8(0x81, 0x00)
     self._write_u8(0xFF, 0x06)
     self._write_u8(0x83, self._read_u8(0x83) & ~0x04)
     self._write_u8(0xFF, 0x01)
     self._write_u8(0x00, 0x01)
     self._write_u8(0xFF, 0x00)
     self._write_u8(0x80, 0x00)
     return (count, is_aperture)
コード例 #9
0
    def distance_in_cm(self):
        start = 0
        end = 0

        # Create a microseconds counter.
        #micros = pyb.Timer(2, prescaler=83, period=0x3fffffff)
        #micros.counter(0)

        # Send a 10us pulse.
        self.trigger.high()
        time.sleep_us(10)
        #pyb.udelay(10)
        self.trigger.low()

        # Wait 'till whe pulse starts.
        while self.echo.value() == 0:
            start = time.ticks_us()

        # Wait 'till the pulse is gone.
        while self.echo.value() == 1:
            end = time.ticks_us()

        # Deinit the microseconds counter
        # micros.deinit()

        # take time different between start and end pulse.
        differ = time.ticks_diff(start, end)

        # Calc the duration of the recieved pulse, divide the result by
        # 2 (round-trip) and divide it by 29 (the speed of sound is
        # 340 m/s and that is 29 us/cm).
        dist_in_cm = (differ / 2) / 29

        return dist_in_cm
コード例 #10
0
def ping(trigPin, echoPin):
    trig = Pin(trigPin, Pin.OUT)
    echo = Pin(echoPin, Pin.IN)
    trig.value(1)
    time.sleep_us(10)
    trig.value(0)
    count = 0
    timeout = False
    start = time.ticks_us()
    while not echo.value():  #wait for HIGH
        time.sleep_us(10)
        count += 1
        if count > 100000:  #over 1s timeout
            timeout = True
            break
    if timeout:  #timeout return 0
        duration = 0
    else:  #got HIGH pulse:calculate duration
        count = 0
        start = time.ticks_us()
        while echo.value():  #wait for LOW
            time.sleep_us(10)
            count += 1
            if count > 2320:  #over 400cm range:quit
                break
        duration = time.ticks_diff(time.ticks_us(), start)
    return duration
コード例 #11
0
ファイル: fastLED_8.py プロジェクト: bvhest/IoT-01_Playground
def timer(f, n):
    t0 = time.ticks_us()
    f(n)
    t1 = time.ticks_us()
    dt = time.ticks_diff(t1, t0)
    fmt = "{:5.3f} s, {:6.3f} uSec/blink : {:8.2f} kHz/s"
    print(fmt.format(dt * 1e-6, dt/N, N/dt * 1e3))
コード例 #12
0
    def _get_distance(self):

        self.dio.write_digital(0)
        time.sleep_us(2)
        self.dio.write_digital(1)
        time.sleep_us(10)
        self.dio.write_digital(0)

        t0 = time.ticks_us()
        count = 0
        while count < _TIMEOUT1:
            if self.dio.read_digital():
                break
            count += 1
        if count >= _TIMEOUT1:
            return None

        t1 = time.ticks_us()
        count = 0
        while count < _TIMEOUT2:
            if not self.dio.read_digital():
                break
            count += 1
        if count >= _TIMEOUT2:
            return None

        t2 = time.ticks_us()

        #dt = int((t1 - t0) )
        #if dt > 530:
        #    return None

        distance = ((t2 - t1) / 29.0 / 2.0)  # cm

        return distance
コード例 #13
0
    def distance_in_cm(self):
        start = 0
        end = 0

        self._distance_trigger.on()
        time.sleep_us(10)
        self._distance_trigger.off()

        while self._distance_echo.value() == 0:
            start = time.ticks_us()

        while self._distance_echo.value() == 1:
            end = time.ticks_us()

        diff = time.ticks_diff(start, end)

        # Calc the duration of the recieved pulse, divide the result by
        # 2 (round-trip) and divide it by 29 (the speed of sound is
        # 340 m/s and that is 29 us/cm).
        dist_in_cm = (diff / 2) / 29

        self._distance_cm = -dist_in_cm
        print("Distance: %s cm." % self._distance_cm)
        if self._distance_cm > self._empty_quantity:
            self._distance_cm = self._empty_quantity
        return self._distance_cm
コード例 #14
0
def _get_distance(pin):
    pin.write_digital(0)
    time.sleep_us(2)
    pin.write_digital(1)
    time.sleep_us(10)
    pin.write_digital(0)

    t0 = time.ticks_us()
    count = 0
    while count < _TIMEOUT1:
        if pin.read_digital():
            break
        count += 1
    if count >= _TIMEOUT1:
        return -1

    t1 = time.ticks_us()
    count = 0
    while count < _TIMEOUT2:
        if not pin.read_digital():
            break
        count += 1
    if count >= _TIMEOUT2:
        return -1
    t2 = time.ticks_us()
    dt = int(time.ticks_diff(t1, t0))

    if dt > 5300:
        return -1
    distance = (time.ticks_diff(t2, t1) / 29 / 2)  # cm
    return distance
コード例 #15
0
    def get_distance_cm(self):
        # send pulse
        self.pin.init(Pin.OUT)
        self.pin.value(0)
        time.sleep_us(2)
        self.pin.value(1)
        time.sleep_us(10)
        self.pin.value(0)

        # listen for response
        self.pin.init(Pin.IN)

        # wait for on
        t0 = time.ticks_us()
        count = 0
        while count < 10000:
            if self.pin.value():
                break
            count += 1

        # wait for off
        t1 = time.ticks_us()
        count = 0
        while count < 10000:
            if not self.pin.value():
                break
            count += 1

        t2 = time.ticks_us()

        if t1 - t2 < 530:
            return (t2 - t1) / 29 / 2
        else:
            return 0
コード例 #16
0
def distance_in_cm():
    start = 0
    delta = 0

    # Create a microseconds counter.

    tPin.off()
    time.sleep_us(5)

    # Send a 10us pulse.
    tPin.on()
    time.sleep_us(10)
    tPin.off()

    # Wait 'till whe pulse starts.
    while ePin.value() == 0:
        # start = micros.counter()
        start = time.ticks_us()  # get millisecond counter)

    # Wait 'till the pulse is gone.
    while ePin.value() == 1:
        delta = time.ticks_diff(time.ticks_us(),
                                start)  # compute time difference

    dist_in_cm = (delta / 2) / 29

    return dist_in_cm
コード例 #17
0
    def trig_p25(self, pin):

        if self.pin_p25.value() == 1:
            self.start_p25 = time.ticks_us()
        elif self.start_p25 is not 0:
            self.result_p25 = time.ticks_diff(self.start_p25, time.ticks_us())
            self.start_p25 = 0
コード例 #18
0
def get_distance(pin):

    # send pulse
    pin.init(machine.Pin.OUT)
    pin.value(0)
    time.sleep_us(2)
    pin.value(1)
    time.sleep_us(10)
    pin.value(0)

    # listen for response
    pin.init(machine.Pin.IN)

    # wait for on
    t0 = time.ticks_us()
    count = 0
    while count < 10000:
        if pin.value():
            break
        count += 1

    # wait for off
    t1 = time.ticks_us()
    count = 0
    while count < 10000:
        if not pin.value():
            break
        count += 1

    t2 = time.ticks_us()

    if t1 - t2 > 530:
        return None
    else:
        return (t2 - t1) / 29 / 2
コード例 #19
0
    def trig_p10(self, pin):

        if self.pin_p10.value() == 1:
            self.start_p10 = time.ticks_us()
        elif self.start_p10 is not 0:
            self.result_p10 = time.ticks_diff(self.start_p10, time.ticks_us())
            self.start_p10 = 0
コード例 #20
0
    def distance_in_cm(self):
        start = 0
        end = 0

        # Create a microseconds counter.
        start=time.ticks_us()
        

        # Send a 10us pulse.
        self.trigger.on()
        time.sleep_us(20)
        self.trigger.off()

        # Wait 'till whe pulse starts.
        while self.echo.value() == 0:
            start = time.ticks_us()

        # Wait 'till the pulse is gone.
        while self.echo.value() == 1:
            end = time.ticks_us()

       
       

        # Calc the duration of the recieved pulse, divide the result by
        # 2 (round-trip) and divide it by 29 (the speed of sound is
        # 340 m/s and that is 29 us/cm).
        dist_in_cm = ((end - start) / 2) / 29

        return dist_in_cm
コード例 #21
0
    def distance_in_cm(self):
        start = 0
        end = 0

        # Send a 10us pulse.
        self.trigger.on()
        time.sleep_us(10)
        self.trigger.off()

        # Wait 'till whe pulse starts.
        while self.echo.value() == 0:
            start = time.ticks_us()

        # Wait 'till the pulse is gone.
        while self.echo.value() == 1:
            end = time.ticks_us()

        # take time different between start and end pulse.
        differ = time.ticks_diff(start, end)

        # Calc the duration of the recieved pulse, divide the result by
        # 2 (round-trip) and divide it by 29 (the speed of sound is
        # 340 m/s and that is 29 us/cm).
        dist_in_cm = (differ / 2) / 29

        return -dist_in_cm
コード例 #22
0
 def _echoRead(self, pin, index):
     if pin.value():
         self.echos[index]['start'] = time.ticks_us()
     elif self.echos[index]['end'] == 0:
         self.timer.deinit()
         self.echos[index]['end'] = time.ticks_us()
         micropython.schedule(self._measureNextRef, 0)
コード例 #23
0
def ping(trigPin, echoPin):
    '''
        return: distance (cm)
    '''
    trig=Pin(trigPin, Pin.OUT)
    echo=Pin(echoPin, Pin.IN)
    trig.value(1)
    time.sleep_us(10)
    trig.value(0)
    timeout=False
    tm_start=time.ticks_us() 
    while not echo.value(): #wait for HIGH, 3000us timeout
        if(time.ticks_diff(time.ticks_us(), tm_start)>3000):
            timeout=True
            break
    if timeout: #timeout return 0
        pass
    else: #got HIGH pulse:calculate duration
        tm_start=time.ticks_us()
        tm_delta = 0
        while echo.value(): #wait for LOW
            tm_delta = time.ticks_diff(time.ticks_us(), tm_start)
            if(tm_delta>3000):
                timeout=True
                break
        if timeout:
            pass
        else:
            tm_delta = time.ticks_diff(time.ticks_us(), tm_start)
            duration=tm_delta
    
    if timeout:
        return 999 #cm, for timeout
        
    return duration/58
コード例 #24
0
ファイル: main.py プロジェクト: waheb2020/ts-lora
def sync():
    global lora
    global index
    global lora_sock
    global active_tx
    global active_rx
    global proc_gw
    global sack_rcv
    global sack_bytes
    lora.init(mode=LoRa.LORA, rx_iq=True, region=LoRa.EU868, frequency=freqs[my_sf-5], power_mode=LoRa.ALWAYS_ON, bandwidth=my_bw, sf=my_sf)
    sync_start = time.ticks_us()
    sack_rcv = 0
    pycom.rgbled(white)
    print("Waiting for sync...")
    lora_sock.settimeout(None)
    while (True):
        machine.idle()
        recv_pkg = lora_sock.recv(100)
        if (len(recv_pkg) > 2):
            recv_pkg_len = recv_pkg[1]
            recv_pkg_id = recv_pkg[0]
            if (int(recv_pkg_id) == (my_sf-5)):
                sack_rcv = time.ticks_us()
                dev_id, leng, s_msg = struct.unpack(_LORA_RCV_PKG_FORMAT % recv_pkg_len, recv_pkg)
                s_msg = str(s_msg)[2:]
                s_msg = s_msg[:-1]
                sack_bytes = recv_pkg_len
                (index, proc_gw, acks) = s_msg.split(":")
                (index, proc_gw) = (int(index), int(proc_gw)*1000)
                print("ACK!")
                lora.power_mode(LoRa.SLEEP)
                active_rx += (time.ticks_us() - sync_start)
                break
    print("sync slot lasted (ms):", (time.ticks_us()-sync_start)/1000)
    print("active time during join-sync (rx/tx) (ms):", active_rx/1000, "/", active_tx/1000)
コード例 #25
0
def serve_requests(sock, ip):
    """
    The following block of code defines and calls the
    serve_requests function, which will be in charge
    of serving any requests that are made to the web
    server. The function is called, and then the web
    server is visited by a browser three separate times.
    Each time a request is served, its details are
    printed out
    """
    print('webserver started on http://%s/' % ip)
    print('\t hard-reset device when done')
    start = time.ticks_us()
    while True:
        conn, address = sock.accept()
        print('request:', address)
        request = conn.makefile()
        while True:
            line = request.readline()
            if not line or line == b'\r\n':
                break
        uptime = time.ticks_us() - start  # time.monotonic() - start
        html = TEMPLATE.format(uptime=uptime / 1E06)  # microseconds -> seconds
        conn.send(html)
        conn.close()
コード例 #26
0
    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
コード例 #27
0
def time_it(f, n):
    t0 = time.ticks_us()
    f(n)
    t1 = time.ticks_us()
    dt = tme.ticks_diff(t1, t0)
    fmt = '{:5.3f} sec, {:6.3f} usec/blink : {:8.2f} kblinks/sec'
    print(fmt.format(dt * 1e-6, dt / n, n / dt * 1e3))
コード例 #28
0
def loop():
    trigger = Pin(triggerPort, Pin.OUT)
    echo = Pin(echoPort, Pin.IN)
    print("Ultrasonic Sensor. Trigger Pin=%d and Echo Pin=%d" %
          (triggerPort, echoPort))
    trigger.value(not trigger.value())
    while True:
        # short impulse 10 microsec to trigger
        trigger.value(not trigger.value())
        time.sleep_us(10)
        trigger.value(not trigger.value())
        count = 0
        start = time.ticks_us()  # get time in usec
        # Now loop until echo goes high
        while not echo.value():
            time.sleep_us(10)
            count += 1
            if count > 100:
                print("Counter exceeded")
                break
        duration = time.ticks_diff(start,
                                   time.ticks_us())  # compute time difference
        print("Duration: %f" % duration)

        # After 38ms is out of range of the sensor
        if duration > 38000:
            print("Out of range")
            continue

        # distance is speed of sound [340.29 m/s = 0.034029 cm/us] per half duration
        distance = 0.017015 * duration
        print("Distance: %f cm" % distance)
        time.sleep(2)
コード例 #29
0
    def update_nomag(self, accel, gyro,dt):    # 3-tuples (x, y, z) for accel, gyro
        ax, ay, az = accel                  # Units G (but later normalised)
        gx, gy, gz = (radians(x) for x in gyro) # Units deg/s
        if self.start_time is None:
            self.start_time = time.ticks_us()  # First run
        q1, q2, q3, q4 = (self.q[x] for x in range(4))   # short name local variable for readability
        # Auxiliary variables to avoid repeated arithmetic
        _2q1 = 2 * q1
        _2q2 = 2 * q2
        _2q3 = 2 * q3
        _2q4 = 2 * q4
        _4q1 = 4 * q1
        _4q2 = 4 * q2
        _4q3 = 4 * q3
        _8q2 = 8 * q2
        _8q3 = 8 * q3
        q1q1 = q1 * q1
        q2q2 = q2 * q2
        q3q3 = q3 * q3
        q4q4 = q4 * q4

        # Normalise accelerometer measurement
        norm = sqrt(ax * ax + ay * ay + az * az)
        if (norm == 0):
            return # handle NaN
        norm = 1 / norm        # use reciprocal for division
        ax *= norm
        ay *= norm
        az *= norm

        # Gradient decent algorithm corrective step
        s1 = _4q1 * q3q3 + _2q3 * ax + _4q1 * q2q2 - _2q2 * ay
        s2 = _4q2 * q4q4 - _2q4 * ax + 4 * q1q1 * q2 - _2q1 * ay - _4q2 + _8q2 * q2q2 + _8q2 * q3q3 + _4q2 * az
        s3 = 4 * q1q1 * q3 + _2q1 * ax + _4q3 * q4q4 - _2q4 * ay - _4q3 + _8q3 * q2q2 + _8q3 * q3q3 + _4q3 * az
        s4 = 4 * q2q2 * q4 - _2q2 * ax + 4 * q3q3 * q4 - _2q3 * ay
        norm = 1 / sqrt(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4)    # normalise step magnitude
        s1 *= norm
        s2 *= norm
        s3 *= norm
        s4 *= norm

        # Compute rate of change of quaternion
        qDot1 = 0.5 * (-q2 * gx - q3 * gy - q4 * gz) - self.beta * s1
        qDot2 = 0.5 * (q1 * gx + q3 * gz - q4 * gy) - self.beta * s2
        qDot3 = 0.5 * (q1 * gy - q2 * gz + q4 * gx) - self.beta * s3
        qDot4 = 0.5 * (q1 * gz + q2 * gy - q3 * gx) - self.beta * s4

        # Integrate to yield quaternion
        deltat = elapsed_micros(self.start_time) / 1000000
        self.start_time = time.ticks_us()
        q1 += qDot1 * deltat
        q2 += qDot2 * deltat
        q3 += qDot3 * deltat
        q4 += qDot4 * deltat
        norm = 1 / sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4)    # normalise quaternion
        self.q = q1 * norm, q2 * norm, q3 * norm, q4 * norm
        self.heading = 0
        self.pitch = degrees(-asin(2.0 * (self.q[1] * self.q[3] - self.q[0] * self.q[2])))
        self.roll = degrees(atan2(2.0 * (self.q[0] * self.q[1] + self.q[2] * self.q[3]),
            self.q[0] * self.q[0] - self.q[1] * self.q[1] - self.q[2] * self.q[2] + self.q[3] * self.q[3]))
コード例 #30
0
    def get_distance(self):
        # Delay measurement if measure frequency is too high in order to avoid overlapping echos.
        time_to_next_measurement = 3 * Ultrasonic._MAX_ULTRASONIC_TRAVEL_TIME - \
            (ticks_us() - Ultrasonic._last_trigger_us)
        if time_to_next_measurement > 0:
            sleep_us(time_to_next_measurement)

        # Reset pins
        self.echo_pin.read_digital()
        self.trig_pin.write_digital(0)
        sleep_us(2)

        # Trigger sound
        Ultrasonic._last_trigger_us = ticks_us()
        self.trig_pin.write_digital(1)
        sleep_us(10)
        self.trig_pin.write_digital(0)

        # Read echo travel time
        travel_time = time_pulse_us(self.echo_pin, 1,
                                    Ultrasonic._MAX_ULTRASONIC_TRAVEL_TIME)
        if travel_time <= 0:
            travel_time = Ultrasonic._MAX_ULTRASONIC_TRAVEL_TIME

        # Return distance
        return travel_time // self.distance_unit
コード例 #31
0
ファイル: mixgo.py プロジェクト: radiumray/mdxly
 def checkdist(self):
  self.trig.value(0)
  self.echo.value(0)
  self.trig.value(1)
  time.sleep_us(10)
  self.trig.value(0)
  while(self.echo.value()==0):
   pass
  t1=time.ticks_us()
  while(self.echo.value()==1):
   pass
  t2=time.ticks_us()
  return round(time.ticks_diff(t2,t1)/10000*340/2,2)
コード例 #32
0
ファイル: sonic.py プロジェクト: iitzex/MicroPython-NodeMCU
def measure():
    Trig.low()
    sleep_us(15)
    Trig.high()
    sleep_us(15)
    Trig.low()
    while(Echo.value() == 0):
        start = ticks_us()
    while(Echo.value() == 1):
        end = ticks_us()
    duration = end - start
    dist = 0.03435 * 0.5 * duration
    print("duration: " + str(duration) + ", " + \
          "distance: " + str(dist))
    return dist
コード例 #33
0
ファイル: stepper.py プロジェクト: Woz4tetra/Atlas
 def step(self, num_steps):
     if time.ticks_diff(self.time0, time.ticks_ms()) > self.delay:
         steps_left = abs(num_steps)
         
         if num_steps > 0: self.direction = True
         if num_steps < 0: self.direction = False
         
         # decrement the number of steps, moving one step each time:
         while steps_left > 0:
             now = time.ticks_us()
             
             # move only if the appropriate delay has passed:
             if time.ticks_diff(self.last_step_time, now) >= self.step_delay:
                 self.last_step_time = now
                 
                 if self.direction:
                     self.step_number += 1
                     if self.step_number == self.step_num:
                         self.step_number = 0
                 else:
                     if self.step_number == 0:
                        self.step_number = self.step_num
                     self.step_number -= 1
                 steps_left -= 1
                 
                 self.step_motor(self.step_number % 4)
         self.time0 = time.ticks_ms()
コード例 #34
0
 def _send_down_link(self, data, tmst, datarate, frequency):
     self.lora.init(mode=LoRa.LORA, frequency=frequency, bandwidth=LoRa.BW_125KHZ,
                    sf=self._dr_to_sf(datarate), preamble=8, coding_rate=LoRa.CODING_4_5,
                    tx_iq=True)
     while time.ticks_us() < tmst:
         pass
     self.lora_sock.send(data)
コード例 #35
0
	def changingEdge(self, pin):
		global callback

		# Get the flag which enabled to IRQ
		flags = callback.flags()
		# If rising, start count the time
		if flags & Pin.IRQ_RISING:
			self.raising_time = time.ticks_us()
		# If falling edge, then stop counting the time and calculate the distance
		elif flags & Pin.IRQ_FALLING:
			self.falling_time = time.ticks_us()
			# Get the ellapsed time between RISING and FALLING
			delay = time.ticks_diff(self.raising_time, self.falling_time)
			# We use 17 instead of 0,017
			distance = delay * 17
			# We rescale the distance in cm by separating cm and mm
			self.cm = distance // 1000
			self.mm = distance % 1000
		
			#in case we have a distance like 49028
			# cm = 49
			# mm = 028 but the 0 would be discared so we check it
			if distance % 100 == distance % 1000:
				self.mm_decimal = "0"
コード例 #36
0
 def _lora_cb(self, lora):
     events = lora.events()
     if events & LoRa.RX_PACKET_EVENT:
         self.rxnb += 1
         self.rxok += 1
         rx_data = self.lora_sock.recv(256)
         stats = lora.stats()
         #self._push_data(self._make_node_packet(rx_data, self.rtc.now(), stats.rx_timestamp, stats.sfrx, stats.rssi, stats.snr))
         # Fix the "not joined yet" issue: https://forum.pycom.io/topic/1330/lopy-lorawan-gateway-with-an-st-lorawan-device/2
         self._push_data(self._make_node_packet(rx_data, self.rtc.now(), time.ticks_us(), stats.sfrx, stats.rssi, stats.snr))
         self.rxfw += 1
     if events & LoRa.TX_PACKET_EVENT:
         self.txnb += 1
         lora.init(mode=LoRa.LORA, frequency=self.frequency, bandwidth=LoRa.BW_125KHZ,
                   sf=self.sf, preamble=8, coding_rate=LoRa.CODING_4_5, tx_iq=True)
コード例 #37
0
 def _udp_thread(self):
     while True:
         try:
             data, src = self.sock.recvfrom(1024)
             _token = data[1:3]
             _type = data[3]
             if _type == PUSH_ACK:
                 print("Push ack")
             elif _type == PULL_ACK:
                 print("Pull ack")
             elif _type == PULL_RESP:
                 self.dwnb += 1
                 ack_error = TX_ERR_NONE
                 tx_pk = json.loads(data[4:])
                 tmst = tx_pk["txpk"]["tmst"]
                 t_us = tmst - time.ticks_us() - 5000
                 if t_us < 0:
                     t_us += 0xFFFFFFFF
                 if t_us < 20000000:
                     self.uplink_alarm = Timer.Alarm(handler=lambda x: self._send_down_link(binascii.a2b_base64(tx_pk["txpk"]["data"]),
                                                                                            tx_pk["txpk"]["tmst"] - 10, tx_pk["txpk"]["datr"],
                                                                                            int(tx_pk["txpk"]["freq"] * 1000000)), us=t_us)
                 else:
                     ack_error = TX_ERR_TOO_LATE
                     print("Downlink timestamp error!, t_us:", t_us)
                 self._ack_pull_rsp(_token, ack_error)
                 print("Pull rsp")
         except socket.timeout:
             pass
         except OSError as e:
             if e.errno == errno.EAGAIN:
                 pass
             else:
                 print("UDP recv OSError Exception")
         except Exception:
             print("UDP recv Exception")
         # Wait before trying to receive again
         time.sleep(0.025)
コード例 #38
0
ファイル: is_wife_home.py プロジェクト: PinkInk/upylib
def main():
    
    #-----------------------------------------------
    #RUN PARAMETERS ... edit;
    #
    #agent to poll
    agent_ip = "192.168.1.1"
    agent_port = 161
    agent_community = "public"
    #wifes (not my wifes) smartphone MAC Address
    mac = b"f437b76dbc64"
    #pin number that neopixel data-in is connected to
    np_pin = 4
    #number of neopixels in string
    np_count = 8
    #inter-poll delay, in seconds
    delay = 1
    #-----------------------------------------------
    
    #the oids in the PAT table
    oids_pat = ("1.3.6.1.2.1.3.1.1.1","1.3.6.1.2.1.3.1.1.2","1.3.6.1.2.1.3.1.1.3")
    #the oid in the table that contains the mac
    oid_mac = "1.3.6.1.2.1.3.1.1.2"
    #the oid of the next entry after the end of the table
    oid_next = "1.3.6.1.2.1.4.1.0"

    np = neopixel.NeoPixel(machine.Pin(np_pin), np_count)

    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    s.settimeout(1)

    gc.collect()

    #build a getnextrequest packet
    greq = usnmp.SnmpPacket(type=usnmp.SNMP_GETNEXTREQUEST, community=agent_community, id=time.ticks_us())
    for oid in oids_pat:
        greq.varbinds[oid] = None

    while True:
        
        gc.collect()
        
        #send getnextrequest
        s.sendto(greq.tobytes(), (agent_ip, agent_port))
        d = s.recvfrom(1024)
        
        #decode the response
        gresp = usnmp.SnmpPacket(d[0])
        
        ishome = False
        endpat = False
        while endpat == False:
        
            gc.collect()
            
            #walk the returned oid/values
            for oid in gresp.varbinds:
            
                #if this one contains a mac
                if oid.startswith(oid_mac):
                
                    #compare it to the mac were looking for
                    if ubinascii.hexlify(gresp.varbinds[oid][1]) == mac:
                        ishome = True
                
                #check for the end of the table
                if oid.startswith(oid_next):
                    endpat = True 
            
            #turn the response into a request ...
            gresp.type = usnmp.SNMP_GETNEXTREQUEST
            gresp.id = time.ticks_us()
            for oid in gresp.varbinds:
                gresp.varbinds[oid] = None
            
            s.sendto(gresp.tobytes(), (agent_ip, agent_port))
            d = s.recvfrom(1024)
            gresp = usnmp.SnmpPacket(d[0])

        print(ishome)
        
        #light the led according to whether she is home
        for i in range(np_count):
            np[i] = (255,0,0) if ishome else (0,255,0)
        
        np.write()

        time.sleep(delay)
コード例 #39
0
ファイル: time.py プロジェクト: jlillest/micropython
spot_test(          1,  (2000,  1,  1,  0,  0,  1, 5,   1))
spot_test(         59,  (2000,  1,  1,  0,  0, 59, 5,   1))
spot_test(         60,  (2000,  1,  1,  0,  1,  0, 5,   1))
spot_test(       3599,  (2000,  1,  1,  0, 59, 59, 5,   1))
spot_test(       3600,  (2000,  1,  1,  1,  0,  0, 5,   1))
spot_test(         -1,  (1999, 12, 31, 23, 59, 59, 4, 365))
spot_test(  447549467,  (2014,  3,  7, 23, 17, 47, 4,  66))
spot_test( -940984933,  (1970,  3,  7, 23, 17, 47, 5,  66))
spot_test(-1072915199,  (1966,  1,  1,  0,  0,  1, 5,   1))
spot_test(-1072915200,  (1966,  1,  1,  0,  0,  0, 5,   1))
spot_test(-1072915201,  (1965, 12, 31, 23, 59, 59, 4, 365))

t1 = time.time()
time.sleep(2)
t2 = time.time()
print(time.ticks_diff(t1, t2) == 2)

t1 = time.ticks_ms()
time.sleep_ms(50)
t2 = time.ticks_ms()
print(time.ticks_diff(t1, t2) == 50)

t1 = time.ticks_us()
time.sleep_us(1000)
t2 = time.ticks_us()
print(time.ticks_diff(t1, t2) < 2000)

t1 = time.ticks_cpu()
t2 = time.ticks_cpu()
print(time.ticks_diff(t1, t2) < 16384)
コード例 #40
0
ファイル: vumeter.py プロジェクト: PinkInk/upylib
def main():

    #-----------------------------------------------
    #RUN PARAMETERS ... edit;
    #
    #agent to poll
    agent_ip = "192.168.1.1"
    agent_port = 161
    agent_community = "public"
    #oid of interface in/out octet to monitor
    #   "1.3.6.1.2.1.2.2.1.10.6" == ifInOctets::6
    #   (my home routers wan interface, vlan1)
    oid_if_inoct = "1.3.6.1.2.1.2.2.1.10.6"
    #expected interface peak throughput in bps
    #   16Mbps;
    bandwidth=16*1024*1024
    #pin number that neopixel data-in is connected to
    np_pin = 4
    #number of neopixels in string
    np_count = 8
    #inter-poll delay, in seconds
    delay = 0.1
    #-----------------------------------------------

    #oid of agent uptime
    #   used to calculate throughput as bits per 1/100s
    #   use agent, rather than mcu (manager), time to 
    #   negate impact of nw latency
    oid_uptime = "1.3.6.1.2.1.1.3.0"

    np = neopixel.NeoPixel(machine.Pin(np_pin), np_count)

    s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    s.settimeout(1)

    vu = []
    for i in range(np_count):
        if i < np_count*60//100:
            vu.append((0,100,0)) #green
        elif i < np_count*80//100:
            vu.append((100,15,0)) #orange
        else:
            vu.append((100,0,0)) #red 

    gc.collect()

    greq = usnmp.SnmpPacket(type=usnmp.SNMP_GETREQUEST, community=agent_community, id=time.ticks_us())
    for i in (oid_uptime, oid_if_inoct):
        greq.varbinds[i] = None

    s.sendto(greq.tobytes(), (agent_ip, agent_port))
    d = s.recvfrom(1024)
    gresp = usnmp.SnmpPacket(d[0])

    while True:
    
        last_ut = gresp.varbinds[oid_uptime][1]
        last_in8 = gresp.varbinds[oid_if_inoct][1]

        gc.collect()

        time.sleep(delay)

        greq.id=time.ticks_us()
        s.sendto(greq.tobytes(), (agent_ip, agent_port))
        d = s.recvfrom(1024)

        gresp = usnmp.SnmpPacket(d[0])

        if greq.id == gresp.id:

            ut = gresp.varbinds[oid_uptime][1]
            in8 = gresp.varbinds[oid_if_inoct][1]

            bps = (in8-last_in8)//(ut-last_ut)*100*8
            level = bps*np_count//bandwidth
            
            print(bps, "bps")

            for i in range(np_count):
                np[i] = vu[i] if level>i else (0,0,0)

            np.write()
コード例 #41
0
def test_features(lcd, orient=lcd160cr.PORTRAIT):
    # if we run on pyboard then use ADC and RTC features
    try:
        import pyb
        adc = pyb.ADCAll(12, 0xf0000)
        rtc = pyb.RTC()
    except:
        adc = None
        rtc = None

    # set orientation and clear screen
    lcd = get_lcd(lcd)
    lcd.set_orient(orient)
    lcd.set_pen(0, 0)
    lcd.erase()

    # create M-logo
    mlogo = framebuf.FrameBuffer(bytearray(17 * 17 * 2), 17, 17, framebuf.RGB565)
    mlogo.fill(0)
    mlogo.fill_rect(1, 1, 15, 15, 0xffffff)
    mlogo.vline(4, 4, 12, 0)
    mlogo.vline(8, 1, 12, 0)
    mlogo.vline(12, 4, 12, 0)
    mlogo.vline(14, 13, 2, 0)

    # create inline framebuf
    offx = 14
    offy = 19
    w = 100
    h = 75
    fbuf = framebuf.FrameBuffer(bytearray(w * h * 2), w, h, framebuf.RGB565)
    lcd.set_spi_win(offx, offy, w, h)

    # initialise loop parameters
    tx = ty = 0
    t0 = time.ticks_us()

    for i in range(300):
        # update position of cross-hair
        t, tx2, ty2 = lcd.get_touch()
        if t:
            tx2 -= offx
            ty2 -= offy
            if tx2 >= 0 and ty2 >= 0 and tx2 < w and ty2 < h:
                tx, ty = tx2, ty2
        else:
             tx = (tx + 1) % w
             ty = (ty + 1) % h

        # create and show the inline framebuf
        fbuf.fill(lcd.rgb(128 + int(64 * math.cos(0.1 * i)), 128, 192))
        fbuf.line(w // 2, h // 2,
            w // 2 + int(40 * math.cos(0.2 * i)),
            h // 2 + int(40 * math.sin(0.2 * i)),
            lcd.rgb(128, 255, 64))
        fbuf.hline(0, ty, w, lcd.rgb(64, 64, 64))
        fbuf.vline(tx, 0, h, lcd.rgb(64, 64, 64))
        fbuf.rect(tx - 3, ty - 3, 7, 7, lcd.rgb(64, 64, 64))
        for phase in (-0.2, 0, 0.2):
            x = w // 2 - 8 + int(50 * math.cos(0.05 * i + phase))
            y = h // 2 - 8 + int(32 * math.sin(0.05 * i + phase))
            fbuf.blit(mlogo, x, y)
        for j in range(-3, 3):
            fbuf.text('MicroPython',
                5, h // 2 + 9 * j + int(20 * math.sin(0.1 * (i + j))),
                lcd.rgb(128 + 10 * j, 0, 128 - 10 * j))
        lcd.show_framebuf(fbuf)

        # show results from the ADC
        if adc:
            show_adc(lcd, adc)

        # show the time
        if rtc:
            lcd.set_pos(2, 0)
            lcd.set_font(1)
            t = rtc.datetime()
            lcd.write('%4d-%02d-%02d %2d:%02d:%02d.%01d' % (t[0], t[1], t[2], t[4], t[5], t[6], t[7] // 100000))

        # compute the frame rate
        t1 = time.ticks_us()
        dt = time.ticks_diff(t1, t0)
        t0 = t1

        # show the frame rate
        lcd.set_pos(2, 9)
        lcd.write('%.2f fps' % (1000000 / dt))
コード例 #42
0
def timeUS(x):
    global atime
    # print(time.ticks_us() - atime)
    if((time.ticks_us() - atime) > 8000):
        actTriac(1)
        atime = time.ticks_us()