Example #1
0
    def wait(self, delay):
        t0 = pyb.millis()
        if delay == 0:
            return
        if delay == -1:
            # if delay == -1 the queue got emptied without stopping the loop
            blue_led.on()
            return
        blue_led.off()
        self._led.on()
        ust = pyb.micros()

        # Do possibly useful things in our idle time
        if delay > 6:
            gct0 = pyb.micros()
            gc.collect()  # we have the time, so might as well clean up
            self.max_gc_us = max(pyb.elapsed_micros(gct0), self.max_gc_us)

        while pyb.elapsed_millis(t0) < delay:
            # Measure the idle time
            # Anything interesting at this point will require an interrupt
            # If not some pin or peripheral or user timer, then it will be
            # the 1ms system-tick interrupt, which matches our wait resolution.
            # So we can save power by waiting for interrupt.
            pyb.wfi()

        self.idle_us += pyb.elapsed_micros(ust)
        self._led.off()
Example #2
0
    def dist(self):
        start = 0
        end = 0

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

        # Wait 'till whe pulse starts.
        start_tout = pyb.micros() + 1000

        while self.echo.value() == 0:
            start = pyb.micros()
            if start > start_tout:
                print("start_tout")
                return -1

        # Wait 'till the pulse is gone.
        end_tout = pyb.micros() + 10000

        while self.echo.value() == 1:
            end = pyb.micros()
            if end > end_tout:
                print("end_tout")
                return -1

        # 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

        return dist_in_cm
Example #3
0
def ramp_to_simple_test():
    ramp_test(75, 1000)
    ramp_test(27.9, 2532)
    ramp_test(100, 500)
    ramp_test(-100, 2000)
    ramp_test(-79, 574)
    ramp_test(-89, 774)
    ramp_test(0, 1500)
    
    #ramp_test(10, 0): expect 1ms , manual test:

    t1 = pyb.micros()
    ramp_time = 0
    ramp_time_expected = 1
    power = 6
    m_dc.ramp_to_simple(power, ramp_time)
    t2 = pyb.micros()
    delta_time = (t2-t1)/1000
    pw = m_dc.get_power()
    print('ramp')
    print('dt: %s, dt_expected: %s' % (delta_time, ramp_time_expected) )
    print('power: %s, power_expected: %s' % (pw, power) )
    within_offset_dt  = value_within_offset(delta_time, ramp_time_expected, 0.3)
    within_offset_pw  = value_within_offset(pw, power, 0.01)
    assert within_offset_dt
    assert within_offset_pw

    m_dc.ramp_to_simple(0,100)
Example #4
0
def balance():
    gangle = 0.0
    start = pyb.micros()
    controlspeed = 0
    fspeed = 0
    while abs(gangle) < 45:  # give up if inclination angle >=45 degrees
        angle  = imu.pitch()
        rate   = imu.get_gy()
        gangle = compf(gangle, angle, rate, pyb.elapsed_micros(start),0.99)         
        start = pyb.micros()
        # speed control
        actualspeed = (motor1.get_speed()+motor2.get_speed())/2
        fspeed = 0.95 * fspeed + 0.05 * actualspeed
        cmd = radio.poll() # cmd[0] is turn speed, cmd[1] is fwd/rev speed
        tangle = speedcontrol(800*cmd[1],fspeed)
         # stability control
        controlspeed += stability(tangle, gangle, rate)           
        controlspeed = constrain(controlspeed,-MAX_VEL,MAX_VEL)
        # set motor speed
        motor1.set_speed(-controlspeed-int(300*cmd[0]))
        motor2.set_speed(-controlspeed+int(300*cmd[0]))
        pyb.udelay(5000-pyb.elapsed_micros(start))
    # stop and turn off motors
    motor1.set_speed(0)
    motor2.set_speed(0)
    motor1.set_off()
    motor2.set_off()
Example #5
0
def ppt():
    """ 
    Pyboard times:
    Time to wait for not t
    10
    Time to wait for f
    10
    """

    f =False
    t =True

    print('Time to wait for not t')
    u = pyb.micros()
    while not t: 
        None
    t = pyb.micros()-u
    print (t)

    print('Time to wait for f')
    u = pyb.micros()
    while f: 
        None
    t = pyb.micros()-u
    print (t)
Example #6
0
    def dist(self):
        start = 0
        end = 0

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

        # Wait 'till whe pulse starts.
        start_tout = pyb.micros() + 1000

        while self.echo.value() == 0:
            start = pyb.micros() 
            if start > start_tout:
                print("start_tout")
                return -1

        # Wait 'till the pulse is gone.
        end_tout = pyb.micros() + 10000 

        while self.echo.value() == 1:
            end = pyb.micros() 
            if end > end_tout:
                print("end_tout")
                return -1

        # 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

        return dist_in_cm
Example #7
0
    def process_acquisition(self):
        """Continue processing the acquisition. To be called periodically within the mainloop.
            This is where the state machine keeps track on progress. """
        if self._ms5837 and self._tsys01:
            acquisition_duration = 0
            if self._ms5837_awaiting_valid_measurements:
                start_micro = pyb.micros()
                read_success = self._ms5837.read()
                if read_success:
                    self._ms5837_pressure = self._ms5837.pressure()
                    self._ms5837_temperature = self._ms5837.temperature()
                    self._ms5837_awaiting_valid_measurements = False

                acquisition_duration += pyb.elapsed_micros(start_micro)

            pyb.delay(10)  # in ms
            if self._tsys01_awaiting_valid_measurements:
                start_micro = pyb.micros()
                read_success = self._tsys01.read()
                if read_success:
                    self._tsys01_temperature = self._tsys01.temperature()
                    self._tsys01_awaiting_valid_measurements = False

                acquisition_duration += pyb.elapsed_micros(start_micro)

            self._acquisition_duration = acquisition_duration

        else:
            raise Exception("Sensors are not initialized!")
Example #8
0
 def getcal(self, minutes=5):
     rtc.calibration(0)  # Clear existing cal
     self.save_time()  # Set DS3231 from RTC
     self.await_transition(
     )  # Wait for DS3231 to change: on a 1 second boundary
     tus = pyb.micros()
     st = rtc.datetime()[7]
     while rtc.datetime()[7] == st:  # Wait for RTC to change
         pass
     t1 = pyb.elapsed_micros(
         tus)  # t1 is duration (uS) between DS and RTC change (start)
     rtcstart = nownr()  # RTC start time in mS
     dsstart = utime.mktime(self.get_time())  # DS start time in secs
     pyb.delay(minutes * 60000)
     self.await_transition()  # DS second boundary
     tus = pyb.micros()
     st = rtc.datetime()[7]
     while rtc.datetime()[7] == st:
         pass
     t2 = pyb.elapsed_micros(
         tus)  # t2 is duration (uS) between DS and RTC change (end)
     rtcend = nownr()
     dsend = utime.mktime(self.get_time())
     dsdelta = (
         dsend - dsstart
     ) * 1000000  # Duration (uS) between DS edges as measured by DS3231
     rtcdelta = (
         rtcend - rtcstart
     ) * 1000 + t1 - t2  # Duration (uS) between DS edges as measured by RTC and corrected
     ppm = (1000000 * (rtcdelta - dsdelta)) / dsdelta
     return int(-ppm / 0.954)
Example #9
0
def balance():
    gangle = 0.0
    start = pyb.micros()
    controlspeed = 0
    fspeed = 0
    while abs(gangle) < 45:  # give up if inclination angle >=45 degrees
        angle = imu.pitch()
        rate = imu.get_gy()
        gangle = compf(gangle, angle, rate, pyb.elapsed_micros(start), 0.99)
        start = pyb.micros()
        # speed control
        actualspeed = (motor1.get_speed() + motor2.get_speed()) / 2
        fspeed = 0.95 * fspeed + 0.05 * actualspeed
        cmd = radio.poll()  # cmd[0] is turn speed, cmd[1] is fwd/rev speed
        tangle = speedcontrol(800 * cmd[1], fspeed)
        # stability control
        controlspeed += stability(tangle, gangle, rate)
        controlspeed = constrain(controlspeed, -MAX_VEL, MAX_VEL)
        # set motor speed
        motor1.set_speed(-controlspeed - int(300 * cmd[0]))
        motor2.set_speed(-controlspeed + int(300 * cmd[0]))
        pyb.udelay(5000 - pyb.elapsed_micros(start))
    # stop and turn off motors
    motor1.set_speed(0)
    motor2.set_speed(0)
    motor1.set_off()
    motor2.set_off()
Example #10
0
    def update_nomag(self, accel, gyro):  # 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 = pyb.micros()  # 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 = pyb.elapsed_micros(self.start_time) / 1000000
        self.start_time = pyb.micros()
        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
Example #11
0
def intCH4(line):
    global ch_up,ch_up_set,fresh
    if pin( ch_pin[3]  ):
        ch_up[3] = pyb.micros()
    else:
        ch_up[4] = pyb.micros()
        for i in range(5):
            ch_up_set[i] = ch_up[i]
        fresh = True
Example #12
0
def timing():           # Test removes overhead of pyb function calls
    t = pyb.micros()
    fir(data, coeffs, 100)
    t1 = pyb.elapsed_micros(t)
    t = pyb.micros()
    fir(data, coeffs, 100)
    fir(data, coeffs, 100)
    t2 = pyb.elapsed_micros(t)
    print(t2-t1,"uS")
Example #13
0
def timing():
    t = pyb.micros()
    avg(data, 10)
    t1 = pyb.elapsed_micros(t)  # Time for one call with timing overheads
    t = pyb.micros()
    avg(data, 10)
    avg(data, 10)
    t2 = pyb.elapsed_micros(t)  # Time for two calls with timing overheads
    print(t2 - t1, "uS")  # Time to execute the avg() call
Example #14
0
 def renderImageTest(self,
                     cached=True,
                     path='images',
                     cpath='cache'):  # images/cache path
     starttime = pyb.micros() // 1000
     for image in os.listdir(path):
         if image != cpath and image.endswith('bmp'):
             self.renderBmp(image, cached=cached, bgcolor=BLACK)
     return (pyb.micros() // 1000 - starttime) / 1000
Example #15
0
    def update_nomag(self, accel, gyro):    # 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 = pyb.micros()  # 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 = pyb.elapsed_micros(self.start_time) / 1000000
        self.start_time = pyb.micros()
        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
Example #16
0
def erase_chip():
    cs.low()
    spi.send(CMD_WRITE_ENABLE)
    cs.high()
    cs.low()
    spi.send(CMD_ERASE_CHIP)
    cs.high()
    t = pyb.micros()
    wait()
    t = pyb.micros() - t
    print ("erase chip",t)
Example #17
0
 def getTempHum(self, buzz=True):
     id_bit = 0 # identificador del bit que estamos tratando
     vbit = 0  # valor de la palabra de 40 bits que se lee, incluye checksum
     self.oneWire.init(pyb.Pin.OUT_PP)
     self.oneWire.high()
     retardo=250
     if buzz:
         #suena buzzer
         self.ch2.pulse_width(12000)
         pyb.delay(80) #in msecs
         self.ch2.pulse_width(0)
         retardo=170
     #pull the pin high and wait 250 milliseconds (ya esta en high, esperamos 250ms de todos modos)
     pyb.delay(retardo)
     #Host pulls low 1.5 ms
     start = pyb.micros()
     self.oneWire.low()
     pyb.udelay(1500)
     #Host pulls up 30us
     self.oneWire.high()
     pyb.udelay(30)
     #Paso a INPUT
     self.oneWire.init(pyb.Pin.IN)
     #sensor pulls low 80us
     while self.oneWire.value() != 0:
         pass
     #sensor pulls up 80us
     while self.oneWire.value() != 1:
         pass
     #sensor pulls low 50us // start bit
     while self.oneWire.value() != 0:
         pass
     while(True):
         #bit starts
         while self.oneWire.value() != 1:
             pass
         start = pyb.micros()
         #bit ends
         while self.oneWire.value() != 0:
             pass
         if (pyb.micros()-start) > 50:
             vbit = (vbit << 1) | 0x1 
         else:
             vbit = (vbit << 1)
         id_bit = id_bit + 1
         if id_bit >= 40:
             check_rec = vbit & 0xff   # checksum recibido
             vbit = vbit >> 8  #aqui "vbit" contiene el valor medido (32 bits)
             check_cal = (vbit & 0xff) + ((vbit >> 8) & 0xff) + ((vbit >> 16) & 0xff) + ((vbit >> 24) & 0xff) # checksum calculado 
             if check_cal != check_rec:
                 self.frt.setAlarmBit(2)
             break
     return vbit
Example #18
0
 def integrate_continuously(self, nap=10):
     #print("integrating continuously, napping %d" % nap)
     tscale = 1 / 1000000
     then = pyb.micros()
     #should_be_less_than = (nap + 30) * 1000
     while True:
         dt = pyb.elapsed_micros(then)
         #if dt >= should_be_less_than:
         #    print("integration dt was", dt)
         then = pyb.micros()
         self.integrate(dt * tscale)
         self.show_balls()
         yield from sleep(nap)
Example #19
0
def testfunc(a):
    start = pyb.micros()
    while not a.mag_ready:
        pass
    dt = pyb.elapsed_micros(start)
    print("Wait time = {:5.2f}mS".format(dt / 1000))
    start = pyb.micros()
    xyz = a.mag.xyz
    dt = pyb.elapsed_micros(start)
    print("Time to get = {:5.2f}mS".format(dt / 1000))
    print("x = {:5.3f} y = {:5.3f} z = {:5.3f}".format(xyz[0], xyz[1], xyz[2]))
    print("Mag status should be not ready (False): ", a.mag_ready)
    print("Correction factors: x = {:5.3f} y = {:5.3f} z = {:5.3f}".format(
        a.mag_correction[0], a.mag_correction[1], a.mag_correction[2]))
Example #20
0
def erase(cmd,addr):
    cs.low()
    spi.send(CMD_WRITE_ENABLE)
    cs.high()
    cs.low()
    spi.send(cmds[cmd])
    spi.send(addr>>16)
    spi.send(addr>>8)
    spi.send(addr)
    cs.high()
    t = pyb.micros()
    wait()
    t = pyb.micros() - t
    print ("erase",cmd,t,'us')
Example #21
0
def ramp_test(power, ramp_time):
    t1 = pyb.micros()
    #ramp_time = 1000
    #power = 75
    m_dc.ramp_to_simple(power, ramp_time)
    t2 = pyb.micros()
    delta_time = (t2-t1)/1000
    pw = m_dc.get_power()
    print('ramp')
    print('dt: %s, dt_expected: %s' % (delta_time, ramp_time) )
    print('power: %s, power_expected: %s' % (pw, power) )
    within_percent_dt   = value_within_percentage(delta_time, ramp_time, 5)
    within_offset_pw   = value_within_offset(pw, power, 0.01)
    assert within_percent_dt
    assert within_offset_pw
Example #22
0
 def renderImageTest(self,
                     cached=True,
                     path=imgdir,
                     cpath=cachedir,
                     delay=0,
                     bgcolor=BLACK):  # images/cache path
     starttime = pyb.micros() // 1000
     cachelist = os.listdir(imgcachepath)
     print(cachedir + 'd ' + imgdir + ':', cachelist)
     for image in os.listdir(path):
         if image != cpath and image.endswith('bmp'):
             self.renderBmp(image, cached=cached, bgcolor=bgcolor)
             if delay:
                 pyb.delay(delay)
     return (pyb.micros() // 1000 - starttime) / 1000
Example #23
0
 def erase(self, cmd, addr):
     self.cs.low()
     self.spi.send(CMD_WRITE_ENABLE)
     self.cs.high()
     print("write enable")
     self.cs.low()
     self.spi.send(cmds[cmd])
     self.spi.send(addr >> 16)
     self.spi.send(addr >> 8)
     self.spi.send(addr)
     self.cs.high()
     t = pyb.micros()
     self.wait()
     t = pyb.micros() - t
     print("erase: ", cmd, addr, t, 'us')
Example #24
0
def p(c='X8'):
    """
    time get a pin value
    13
    """
    p = pyb.Pin(c,pyb.Pin.OUT_PP,pull=pyb.Pin.PULL_NONE)
    p.low()
    print(p.value())

    print('time get a pin value')

    u = pyb.micros()
    p.value()
    t = pyb.micros()-u
    print (t)
Example #25
0
def thr_instrument(objSch, lstResult):
    yield  # Don't measure initialisation phase (README.md)
    while True:
        start = pyb.micros()  # More typically we'd measure our own code
        yield  # but here we're measuring yield delays
        lstResult[0] = max(lstResult[0], pyb.elapsed_micros(start))
        lstResult[1] += 1
def thr_instrument(objSch, lstResult):
    yield                          # Don't measure initialisation phase (README.md)
    while True:
        start = pyb.micros()       # More typically we'd measure our own code
        yield                      # but here we're measuring yield delays
        lstResult[0] = max(lstResult[0], pyb.elapsed_micros(start))
        lstResult[1] += 1
Example #27
0
 def reset(self, debug=False):
     """Reset the module and read the boot message.
     ToDo: Interpret the boot message and do something reasonable with
     it, if possible."""
     boot_log = []
     if debug:
         start = micros()
     self._execute_command(CMDS_GENERIC['RESET'], debug=debug)
     # wait for module to boot and messages appearing on self.uart
     timeout = 300
     while not self.uart.any() and timeout > 0:
         delay(10)
         timeout -= 1
     if debug and timeout == 0:
         print("%8i - RX timeout occured!" % (elapsed_micros(start)))
     # wait for messages to finish
     timeout = 300
     while timeout > 0:
         if self.uart.any():
             boot_log.append(self.uart.readline())
             if debug:
                 print("%8i - RX: %s" %
                       (elapsed_micros(start), str(boot_log[-1])))
         delay(20)
         timeout -= 1
     if debug and timeout == 0:
         print("%8i - RTimeout occured while waiting for module to boot!" %
               (elapsed_micros(start)))
     return boot_log[-1].rstrip() == b'ready'
Example #28
0
 def IRQ(self, pin):
     if self.return_pin.value():
         self.start_micros = micros()
     elif self.start_micros is not None:
         self.elapsed = elapsed_micros(self.start_micros)
     else:
         self.bogus = True
Example #29
0
    def read_status_packet(self):
        """Reads a status packet and returns it.

        Rasises a bioloid.bus.BusError if an error occurs.

        """
        pkt = packet.Packet()
        while True:
            start = pyb.micros()
            byte = self.serial_port.read_byte()
            if byte is None:
                raise BusError(packet.ErrorCode.TIMEOUT)
            err = pkt.process_byte(byte)
            if err != packet.ErrorCode.NOT_DONE:
                break
        if err != packet.ErrorCode.NONE:
            raise BusError(err)
        if self.show & Bus.SHOW_COMMANDS:
            log('Rcvd Status: {}'.format(packet.ErrorCode(err)))
        if self.show & Bus.SHOW_PACKETS:
            dump_mem(pkt.pkt_bytes, prefix='  R', show_ascii=True, log=log)
        err = pkt.error_code()
        if err != packet.ErrorCode.NONE:
            raise BusError(err)
        return pkt
Example #30
0
	def tx_rx(self, tx, nr_chars):
		""" Send command to and receive respons from SA7S"""
		''' rx = uart.readall() # Receive respons TAKES 1.0 sec ALWAYS (after uart.any) TimeOut!!!! '''
		i = 0
		rx = ''
		# todo: do check if respons == same as sent: repeat otherwise
		self.uart.write(tx)  # Send to unit
		# print("uart.write: i, tx: ", i,  tx[:-1])
		while True:  # Typiskt 2–3 (search: 4) varv i loopen
			i += 1
			if self.uart.any():  # returns True if any characters wait
				dbg.high()
				strt = micros()
				rx = b''
				j = 0
				while True:  # Typically 10–20 (search: 12; M, R & W0144: 1) loops
					j += 1
					rxb = self.uart.read(nr_chars)  # uart.readln och uart.readall ger båda timeout (1s default)
					rx = rx + rxb
					if (len(rx) >= nr_chars) or (rxb == b'\r'):  # End of search returns \r
						break
				dbg.low()
				##print("uart.read: i, j, tx, rx, ∆time ", i, j, tx[:-1], rx, len(rx), elapsed_micros(strt) / 1e6, 's')
				delay(84)
				break
			else:
				delay(10)
		return rx
Example #31
0
def ni():
    print ('Native: how many instructions can we do in 100 us')
    count = 0
    u = pyb.micros()
    while pyb.elapsed_micros(u) < 100:
        count+=1
    print(count)
Example #32
0
def timing():                           # Check magnetometer call timings
    imu.mag_triggered = False           # May have been left True by above code
    start = pyb.micros()
    imu.get_mag_irq()
    t1 = pyb.elapsed_micros(start)
    start = pyb.micros()
    imu.get_mag_irq()
    t2 = pyb.elapsed_micros(start)
    pyb.delay(200)
    start = pyb.micros()
    imu.get_mag_irq()
    t3 = pyb.elapsed_micros(start)

    # 1st call initialises hardware
    # 2nd call tests it (not ready)
    # 3rd call tests ready (it will be after 200mS) and reads data
    print(t1, t2, t3) # 1st call takes 265uS second takes 175uS. 3rd takes 509uS
def MakeCTRimproved(number):
    """
      Een nummer (de counter) wordt omgezet in een vier op vier matrix.

    :param number: Een getal tussen de 0 en de 2**128-1
    :return matrix: 4x4-matrix
    """
	start = pyb.micros()
def testfunc(a):
    start = pyb.micros()
    while not a.mag_ready:
        pass
    dt = pyb.elapsed_micros(start)
    print("Wait time = {:5.2f}mS".format(dt / 1000))
    start = pyb.micros()
    xyz = a.mag.xyz
    dt = pyb.elapsed_micros(start)
    print("Time to get = {:5.2f}mS".format(dt / 1000))
    print("x = {:5.3f} y = {:5.3f} z = {:5.3f}".format(xyz[0], xyz[1], xyz[2]))
    print("Mag status should be not ready (False): ", a.mag_ready)
    print(
        "Correction factors: x = {:5.3f} y = {:5.3f} z = {:5.3f}".format(
            a.mag_correction[0], a.mag_correction[1], a.mag_correction[2]
        )
    )
Example #35
0
def timing():                           # Check magnetometer call timings
    imu.mag_triggered = False           # May have been left True by above code
    start = pyb.micros()
    imu.get_mag_irq()
    t1 = pyb.elapsed_micros(start)
    start = pyb.micros()
    imu.get_mag_irq()
    t2 = pyb.elapsed_micros(start)
    pyb.delay(200)
    start = pyb.micros()
    imu.get_mag_irq()
    t3 = pyb.elapsed_micros(start)

    # 1st call initialises hardware
    # 2nd call tests it (not ready)
    # 3rd call tests ready (it will be after 200mS) and reads data
    print(t1, t2, t3) # 1st call takes 265uS second takes 175uS. 3rd takes 509uS
Example #36
0
def timeItRunner():
    global start,co,avg,sm,nb
    sm=nb=0
    start=pyb.micros()
    co.value(1)
    while True:
        avg = 0 if not nb else sm/nb
        print('avg:\t' + str(avg))
Example #37
0
def  evaluate(total, lcd):
    lcd.light(False)
    yield
    starttime = pyb.micros()
    yield
    endtime = pyb.micros()
    t = total[0]
    lcd.light(True)
    us = endtime - starttime

    text = "c/s: %f " % (t/ 10)
    lcd.text(text, 0, 10, 1)
    lcd.show()

    log.info("Total micros in 10 second runtime: %f", us / 1000000)
    log.info("Total counts:  %d counts /sec: %f ", t, t / 10)
    yield asyncio.KillOs()
def timer():
    start = pyb.micros()
    #reform_list(([[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]],15,[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]))
    #Encryptie.Vercijfering(12,[255,255,1,0,255,110,211,0,0,255,144,255,0,5,10,240])
    #read(NB_READINGS)
    encrypt(
        [255, 255, 1, 0, 255, 110, 211, 0, 0, 255, 144, 255, 0, 5, 10, 240])
    return pyb.elapsed_micros(start)
Example #39
0
def writerCirc():
    global handlerIndex,outData,tbInData,interruptCounter,period,start
    if outData.nbElts:
        tbInData.put(outData.get())
    else:
        handlerIndex ^=1
    period[interruptCounter] = pyb.elapsed_micros(start)
    interruptCounter+=1
    start=pyb.micros()
Example #40
0
def writer():
    global handlerIndex,outData,interruptCounter,period,start
    if outData.nbElts:
        pdov(outData.get()%2)
    else:
        handlerIndex ^=1
    period[interruptCounter] = pyb.elapsed_micros(start)
    interruptCounter+=1
    start=pyb.micros()
 def test_render_time(self):
     # Rendering takes the expected amount of time
     n = 10
     t0 = pyb.micros()
     for i in range(n):
         self.p.render()
     dt = pyb.elapsed_micros(t0)
     average_ms = dt / (n * 1000)
     print("%d renders average %f ms" % (n, average_ms), end='')
     self.assertTrue(average_ms < 15, "average render time %f ms" % (average_ms))
Example #42
0
def tone1(freq):
    t0 = micros()
    dac = DAC(1)
    while True:
        theta = 2*math.pi*float(elapsed_micros(t0))*freq/1e6
        fv = math.sin(theta)
        v = int(126.0 * fv) + 127
        #print("Theta %f, sin %f, scaled %d" % (theta, fv, v))
        #delay(100)
        dac.write(v)
Example #43
0
def readerCirc():
    global bitsExpected,inData,tbOutData,interruptCounter,period,start
    if bitsExpected == inData.nbElts:
        # we're done
        stop()
    else:
        inData.put(tbOutData.get())
    period[interruptCounter] = pyb.elapsed_micros(start)
    interruptCounter+=1
    start=pyb.micros()
Example #44
0
def pulseIn(pin, value, timeout=100000, width=1000000):
    try:
        if value == LOW:
            v0 = 1
            v1 = 0
        elif value == HIGH:
            v0 = 0
            v1 = 1
        start = pyb.micros()
        while pin.value() == v0:
            if pyb.elapsed_micros(start) > timeout:
                return
        start = pyb.micros()
        while pin.value() == v1:
            if pyb.elapsed_micros(start) >= width:
                break
        return pyb.elapsed_micros(start)
    except:
        pass
Example #45
0
 def test_render_time(self):
     # Rendering takes the expected amount of time
     n = 10
     t0 = pyb.micros()
     for i in range(n):
         self.p.render()
     dt = pyb.elapsed_micros(t0)
     average_ms = dt / (n * 1000)
     print("%d renders average %f ms" % (n, average_ms), end='')
     self.assertTrue(average_ms < 15,
                     "average render time %f ms" % (average_ms))
def nm3_callback(line):
    # NB: You cannot do anything that allocates memory in this interrupt handler.
    global _nm3_callback_flag
    global _nm3_callback_seconds
    global _nm3_callback_millis
    global _nm3_callback_micros
    # NM3 Callback function
    _nm3_callback_micros = pyb.micros()
    _nm3_callback_millis = pyb.millis()
    _nm3_callback_seconds = utime.time()
    _nm3_callback_flag = True
Example #47
0
 def read_sal_from_all(self, start):
     '''
     switches to and reads ADC for all, returns one tuple with the times
     of reads in us and values between 0 and 4096
     '''
     times = [0]*8
     values = [0]*8
     for i in range(1, 9):
         times[i-1] = pyb.micros() - start
         values[i-1] = self.read_sal_from(i)
     return times, values
Example #48
0
def ct(c='X8'):
    bits = 0
    for i in range(5):
        bits = (bits <<2) |2
    #p = pyb.Pin(c,pyb.Pin.OUT_OD,pull=pyb.Pin.PULL_NONE)
    u = pyb.micros()
    while (bits):
        pyb.udelay(50)
        if(bits & 1):
            p = pyb.Pin(c,pyb.Pin.IN,pull=pyb.Pin.PULL_UP)
        else:
            p = pyb.Pin(c,pyb.Pin.OUT_OD,pull=pyb.Pin.PULL_NONE)
            p.low()
        bits = bits >> 1
        #pyb.udelay(10)
    t= pyb.micros()-u
    #p = pyb.Pin(c,pyb.Pin.IN,pull=pyb.Pin.PULL_UP)
    #while not p.value():
    #    print('o')
    print('elapsed time: ' +str(t))
Example #49
0
def tn(c='X8'):
    print ('NATIVE: how many pin values can we do in 100 us')
    p = pyb.Pin(c,pyb.Pin.OUT_PP,pull=pyb.Pin.PULL_NONE)
    bit = 1
    p.value(bit)
    count = 0
    u = pyb.micros()
    while pyb.elapsed_micros(u) < 100:
        bit ^= 1
        p.value(bit)
        count+=1
    print(count)
Example #50
0
def align():
    lcd.clear()
    lcd.text("Acc",0,56,1)
    lcd.text("CompF",64,56,1)
    graphics.drawCircle(lcd,32,26,26,1)
    graphics.drawCircle(lcd,96,26,26,1)
    start = pyb.micros()
    cangle = 90.0
    while abs(cangle)>2.0:
        angle  = imu.pitch()
        cangle = compf(cangle, angle, imu.get_gy(), pyb.elapsed_micros(start),0.91) 
        start = pyb.micros()
        graphics.line(lcd,32,26,angle,24,1)
        graphics.line(lcd,96,26,cangle,24,1)
        lcd.display()
        graphics.line(lcd,32,26,angle,24,0)
        graphics.line(lcd,96,26,cangle,24,0)
    lcd.clear()
    lcd.text("Start balancing!.",0,24,1)
    lcd.text('zero:{:5.2f}'.format(cangle),0,32,1)
    lcd.display()
Example #51
0
def pt(c='X8'):
    p = pyb.Pin(c,pyb.Pin.OUT_PP,pull=pyb.Pin.PULL_NONE)
    p.low()
    print(p.value())

    print('time for LOW output to get PULLED HIGH as input')

    u = pyb.micros()
    p.init(pyb.Pin.IN,pull=pyb.Pin.PULL_UP)
    while not p.value():
        pass
    t = pyb.micros()-u
    print (t)

    print('time for a HIGH input to go to LOW output')
    u = pyb.micros()
    p = pyb.Pin(c,pyb.Pin.OUT_PP,pull=pyb.Pin.PULL_NONE)
    p.low()
    while p.value():
        pass
    t = pyb.micros()-u
    print (t)
    
    print('time for a LOW output to go to HIGH output')
    u = pyb.micros()
    p.value(1)
    while not p.value():
        pass
    t = pyb.micros()-u
    print (t)
Example #52
0
def pppt():
    """
    time to do absolutely nothing.
    9
    time to execute None.
    8
    time to execute 5x None.
    9
    """
    print('time to do absolutely nothing.')
    u = pyb.micros()
    t = pyb.micros()-u
    print (t)

    print('time to execute None.')
    u = pyb.micros()
    None
    t = pyb.micros()-u
    print (t)

    print('time to execute 5x None.')
    u = pyb.micros()
    None
    None
    None
    None
    None
    t = pyb.micros()-u
    print (t)
Example #53
0
def align():
    lcd.clear()
    lcd.text("Acc", 0, 56, 1)
    lcd.text("CompF", 64, 56, 1)
    graphics.drawCircle(lcd, 32, 26, 26, 1)
    graphics.drawCircle(lcd, 96, 26, 26, 1)
    start = pyb.micros()
    cangle = 90.0
    while abs(cangle) > 2.0:
        angle = imu.pitch()
        cangle = compf(cangle, angle, imu.get_gy(), pyb.elapsed_micros(start),
                       0.91)
        start = pyb.micros()
        graphics.line(lcd, 32, 26, angle, 24, 1)
        graphics.line(lcd, 96, 26, cangle, 24, 1)
        lcd.display()
        graphics.line(lcd, 32, 26, angle, 24, 0)
        graphics.line(lcd, 96, 26, cangle, 24, 0)
    lcd.clear()
    lcd.text("Start balancing!.", 0, 24, 1)
    lcd.text('zero:{:5.2f}'.format(cangle), 0, 32, 1)
    lcd.display()
Example #54
0
def blink_micros():
    start = pyb.micros()
    led.on()
    while pyb.elapsed_micros(start) < 100000:
        pass
    led.off()
    while pyb.elapsed_micros(start) < 200000:
        pass
    led.on()
    while pyb.elapsed_micros(start) < 300000:
        pass
    led.off()
    while pyb.elapsed_micros(start) < 1000000:
        pass
Example #55
0
    def t_4_callback(self, tim):
        # Read ADC value and current time
        value = self.adc.read()
        t = pyb.micros() - self.t_start

        # Add value and time to buffer
        self.buf_0[self.buf_index][0] = t
        self.buf_0[self.buf_index][1] = value

        # Increment buffer index until buffer is filled,
        # then disable interrupt and change status
        self.buf_index += 1
        if (self.buf_index >= len(self.buf_0)):
            self.tim.callback(None)
            self.status = 'Store'
def test(spi=3, cs='PB0'):
    print("SPI flash")
    cs = Pin(cs, Pin.OUT_PP)
    spi = SPI(spi, SPI.MASTER, 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 = micros()
    flash.erase(addr, '4k')
    # flash.erase(addr, '32k')
    # flash.erase(addr, '64k')
    # flash.erase_chip()
    t = micros() - t1
    print("erase {} us".format(t))

    print("Writing blocks (256b) at address {}...".format(addr))
    buf = bytearray(range(256))
    t1 = micros()
    flash.write_block(addr, buf)
    t = micros() - 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 = micros()
    flash.read_block(0, buf)
    t = micros() - t1
    mbs = len(buf) * 8. / t
    print("read({}) {} us, {} mbs".format(len(buf), t, mbs))