Exemplo n.º 1
0
def main():
    enabled = False
    led = machine.Pin(2, machine.Pin.OUT)
    trig = machine.Pin(12, machine.Pin.OUT)
    echo = machine.Pin(13, machine.Pin.IN)
    i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4))
    oled = ssd1306.SSD1306_I2C(128, 64, i2c, 0x3c)

    while True:
        trig.off()
        utime.sleep_us(2)
        trig.on()
        utime.sleep_us(10)
        trig.off()
        while echo.value() == 0:
            pass
        t1 = utime.ticks_us()
        while echo.value() == 1:
            pass
        t2 = utime.ticks_us()
        cm = (t2 - t1) / 58.0
        print(cm)
        oled.fill(0)
        oled.text("Distanz: " + str(cm), 0, 0)
        oled.show()
        if enabled:
            led.off()
        else:
            led.on()
        utime.sleep_ms(1000)
        enabled = not enabled
        utime.sleep(2)
Exemplo n.º 2
0
 def write_object_stub(self, fp, object_expr: object, obj_name: str,
                       indent: str):
     if object_expr in self.problematic:
         return
     items, errors = self.get_obj_attributes(object_expr)
     for name, rep, typ, obj in sorted(items, key=lambda x: x[0]):
         if name.startswith("__"):
             continue
         resetWDT()
         sleep_us(1)
         if typ in ["<class 'function'>", "<class 'bound_method'>"]:
             s = indent + "def " + name + "():\n"
             s += indent + "    pass\n\n"
             fp.write(s)
         elif typ in ["<class 'str'>", "<class 'int'>", "<class 'float'>"]:
             s = indent + name + " = " + rep + "\n"
             fp.write(s)
         elif typ == "<class 'type'>" and indent == "":
             s = "\n" + indent + "class " + name + ":\n"
             s += indent + "    ''\n"
             fp.write(s)
             self.write_object_stub(fp, obj,
                                    "{0}.{1}".format(obj_name,
                                                     name), indent + "    ")
         else:
             fp.write(indent + name + " = None\n")
     del items
     del errors
     try:
         del name, rep, typ, obj
     except (OSError, KeyError):
         pass
Exemplo n.º 3
0
    def __init__(self, i2c, address, oneline=False, charsize=LCD_5x8DOTS):

        self.i2c = i2c
        self.address = address

        self.disp_func = self.LCD_DISPLAYON  # | 0x10
        if not oneline:
            self.disp_func |= self.LCD_2LINE
        elif charsize != 0:
            # For 1-line displays you can choose another dotsize
            self.disp_func |= self.LCD_5x10DOTS

        # Wait for display init after power-on
        utime.sleep_ms(50)  # 50ms

        # Send function set
        self.cmd(self.LCD_FUNCTIONSET | self.disp_func)
        utime.sleep_us(4500)  ##time.sleep(0.0045) # 4.5ms
        self.cmd(self.LCD_FUNCTIONSET | self.disp_func)
        utime.sleep_us(150)  ##time.sleep(0.000150) # 150µs = 0.15ms
        self.cmd(self.LCD_FUNCTIONSET | self.disp_func)
        self.cmd(self.LCD_FUNCTIONSET | self.disp_func)

        # Turn on the display
        self.disp_ctrl = self.LCD_DISPLAYON | self.LCD_CURSOROFF | self.LCD_BLINKOFF
        self.display(True)

        # Clear it
        self.clear()

        # Set default text direction (left-to-right)
        self.disp_mode = self.LCD_ENTRYLEFT | self.LCD_ENTRYSHIFTDECREMENT
        self.cmd(self.LCD_ENTRYMODESET | self.disp_mode)
Exemplo n.º 4
0
 def color(self, red, green, blue):
     pulsos = tuple(
         self._sacar_secuencia(green) + self._sacar_secuencia(red) +
         self._sacar_secuencia(blue))
     self.rmt.write_pulses(pulsos, start=1)
     utime.sleep_us(50)
     self.rmt.write_pulses(pulsos, start=1)
Exemplo n.º 5
0
 def getPWR(self):  #en
     RILIM = 130
     KILIM = 365
     GAIN = 12.12
     self.p_SHDN_.value(1)
     utime.sleep_us(10)  #Enable Delay Time from Shutdown
     #ADC.ATTN_0DB (0-1), ADC.ATTN_2_5DB(0-1.33), ADC.ATTN_6DB(0-2), ADC.ATTN_11DB(0-3.55)
     ILIM = VILIM = 0
     ADC_GAIN = [0, 1.334, 1.995, 3.548]
     for i, e in reversed(list(enumerate(ADC_GAIN))):
         adc_ILIM = self.adc.channel(attn=i, pin='P20')
         ILIM = adc_ILIM()
         if ILIM < 2000 and i > 0:
             pass
         else:
             VILIM = adc_ILIM.voltage()
             break
     if ILIM > 0:
         PWIN_I = (KILIM * (VILIM / GAIN)) / (RILIM * 0.8)
     elif self._bq25895.pg_stat(
     ) > 0:  #PYCOM mais prob avec ADC ESP32 pour faible valeur
         PWIN_I = 60.0
     else:
         PWIN_I = 0
     #print("ADC : {}, ADC_v = {}, PWIN_I : {}".format(adc_ILIM(), VILIM, PWIN_I) )
     self.p_SHDN_.value(0)
     l.debug("BQ>ATTN:{}, ILIM:{}, PWIN_I:{}".format(
         ADC_GAINstr[i], ILIM, PWIN_I))
     return PWIN_I
Exemplo n.º 6
0
    def write2LCD_8bits(self, register_select, byte_block, wait_time):
        time = utime.ticks_us()
        if(register_select):
            self.RS.on()

        # MSB
        if(byte_block & 128 > 0):
            self.D7.on()
        if(byte_block & 64 > 0):
            self.D6.on()
        if(byte_block & 32 > 0):
            self.D5.on()
        if(byte_block & 16 > 0):
            self.D4.on()

        # LSB
        if(byte_block & 8 > 0):
            self.D3.on()
        if(byte_block & 4 > 0):
            self.D2.on()
        if(byte_block & 2 > 0):
            self.D1.on()
        if(byte_block & 1 > 0):
            self.D0.on()

        self.E.on()
        if((time + wait_time) - utime.ticks_us() > 0):
            utime.sleep_us((time + wait_time) - utime.ticks_us())
        self.E.off()
        self.RS.off()
        self.D7.off()
        self.D6.off()
        self.D5.off()
        self.D4.off()
Exemplo n.º 7
0
    def execute(self, packet):
        self.wake()
        # Wait tWHI + tWLO
        utime.sleep_us(WAKE_DELAY)

        # Send the command
        self._bus.writeto(self._address, b'\x03' + packet.to_buffer())

        # Delay for execution time
        utime.sleep_ms(packet.delay)

        response = packet.response_data_mv

        # Receive the response
        self._bus.readfrom_into(self._address, response[0:1])
        self._bus.readfrom_into(self._address, response[1:response[0]])

        # Check response
        err, msg = self.is_error(response)
        if err != ATCA_STATUS.ATCA_SUCCESS:
            raise ValueError("execute: 0x{:02x} ({:s}) - {:s}".format(
                err,
                msg,
                ubinascii.hexlify(response),
            ))

        packet.response_data = response[:response[0]]
def test():
    """Bouncing sprite."""
    try:
        # Baud rate of 14500000 seems about the max
        BLK = Pin(BL_Pin, Pin.OUT)
        spi = SPI(baudrate=40000000,
                  miso=Pin(MISO_Pin),
                  mosi=Pin(MOSI_Pin, Pin.OUT),
                  sck=Pin(SCLK_Pin, Pin.OUT))
        display = ST7789(spi,
                         135,
                         240,
                         cs=Pin(CS_Pin),
                         dc=Pin(DC_Pin),
                         rst=None)
        BLK.value(1)
        display.clear()

        # Load sprite
        logo = BouncingSprite('images/Python41x49.raw', 41, 49, 135, 240, 1,
                              display)

        while True:
            timer = ticks_us()
            logo.update_pos()
            logo.draw()
            # Attempt to set framerate to 30 FPS
            timer_dif = 33333 - ticks_diff(ticks_us(), timer)
            if timer_dif > 0:
                sleep_us(timer_dif)

    except KeyboardInterrupt:
        display.cleanup()
Exemplo n.º 9
0
    def __init__(self, i2c, line=2, char_size=LCD_5x8DOTS):
        # public
        self.i2c = i2c
        # private
        self._disp_func = LCD_DISPLAYON | char_size | LCD_2LINE if line == 2 else LCD_1LINE
        self._disp_ctrl = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF
        self._disp_mode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT

        # wait display init after power-on
        sleep_ms(50)

        # send function set
        self.cmd(LCD_FUNCTIONSET | self._disp_func)
        sleep_us(4500)
        self.cmd(LCD_FUNCTIONSET | self._disp_func)
        sleep_us(150)
        self.cmd(LCD_FUNCTIONSET | self._disp_func)
        self.cmd(LCD_FUNCTIONSET | self._disp_func)

        # turn on the display
        self.display(True)

        # clear it
        self.clear()

        # set default text direction (left-to-right)
        self.cmd(LCD_ENTRYMODESET | self._disp_mode)

        # init RGB backlight
        self.i2c.writeto_mem(RGB_ADDR, REG_MODE1, b'\x00')
        self.i2c.writeto_mem(RGB_ADDR, REG_MODE2, b'\x20')
        self.i2c.writeto_mem(RGB_ADDR, REG_OUTPUT, b'\xaa')
Exemplo n.º 10
0
 def read_trace(self):
     self.sampleCount = 0
     self.traceIndex = 0
     self.trigCond = False
     if self.pulse_T < 1:
         delay = self.pulse_T * 1000
     print("Waiting for trigger")
     while not self.trig():
         pass
     else:
         print("Trigger seen")
         self.triggeredAt = self.traceIndex
         print("Triggered at trace buffer index ", self.triggeredAt)
         print("value: ", self.traceBuf[self.traceIndex - 1])
     if self.no_trig:
         maxcount = 500 - 1
     else:
         maxcount = 500 - self.trigPos
     print("maxcount: ", maxcount)
     for i in range(maxcount):
         value = self.adc.read()
         self.traceBuf[self.traceIndex] = value >> 4  # restrict to 8 bits
         self.traceIndex += 1
         if self.traceIndex == 500:  # traceBuf is a circular buffer
             self.traceIndex = 0
         if self.pulse_T < 1:
             sleep_us(delay)
         else:
             sleep_ms(self.pulse_T)
     print("Writing data to disk")
     self.writeToDisk()
Exemplo n.º 11
0
    def distance_cm(self):
        '''Returns the distance from a rangefinder in cm'''
        self.pin.write_digital(0)
        utime.sleep_us(200)
        self.pin.write_digital(1)
        utime.sleep_us(500)
        self.pin.write_digital(0)
        init = utime.ticks_us()
        stop = init
        start = init
        flag = False
        timeout = 100000

        while not self.pin.read_digital():
            if utime.ticks_us() - init > timeout:
                return -1

        start = utime.ticks_us()

        while self.pin.read_digital():
            if utime.ticks_us() - start > timeout:
                return -1

        stop = utime.ticks_us()
        distance = (stop - start) * 343 / 20000
        print(stop, start)
        return distance
Exemplo n.º 12
0
def main():
    i = 0
    while i <= 100:
        txt = '%04d' % i
        tm.show(txt, True)
        i += 1
        utime.sleep_us(1000)
Exemplo n.º 13
0
def measure(N=1000, delay=200):

    asum = 0
    sqsum = 0

    meanVolt = 0
    sqmeanVolt = 0
    rmsVolt = 0
    stdDev = 0

    for i in range(N):
        volt = apin.voltage()

        asum += volt
        sqsum += volt * volt

        sleep_us(delay)

    meanVolt = asum / N
    sqmeanVolt = sqsum / N
    rmsVolt = sqrt(sqmeanVolt)
    stdDev = sqrt(sqmeanVolt - (meanVolt * meanVolt))

    print('meanVoltage:\t{:10.0f} mV'.format(meanVolt))
    print('rmsVoltage:\t{:10.0f} mV'.format(rmsVolt))
    print('stdDev:\t\t{:10.0f} mV'.format(stdDev))
Exemplo n.º 14
0
 def measure_distance(self):
     self.trigger.high()
     utime.sleep_us(10)
     self.trigger.low()
     pulse_time = machine.time_pulse_us(self.echo, 1, 50000)
     print(pulse_time)
     return pulse_time
Exemplo n.º 15
0
 def set_volume(self, volume):
     self.write_byte(0x0A)
     HighByte, LowByte = split(volume)
     self.write_byte(HighByte)
     self.write_byte(LowByte)
     self.write_byte(0x0C)
     sleep_us(2000)
Exemplo n.º 16
0
    def rotate_some(self, dir, times):
        '''
        :param dir:
        :return:
        '''
        print('Rotate')

        self.dir.value(dir)
        #print('it works2')

        for i in range(0, times):
            #print('it works3')

            self.stp.value(1)
            # to_log(1)
            #print('it works4')

            utime.sleep_us(1000)
            #print('it works5')

            self.stp.value(0)
            #print('it works6')

            # to_log(2)
            utime.sleep_us(1000)
Exemplo n.º 17
0
 def main(self, leg_geom):
     """Main loop body is in `self.app_control()`
     """
     self.app_init_hardware()
     self.app_init_software(leg_geom)
     t0 = ticks_us()
     oldLoopStart = 0
     print("Starting NUMA loop...")
     while True:
         #TODO timing? ???
         loopStart = ticks_us()
         #print("------------------------LOOPSTART:", loopStart)
         desired_loop_time = self.app_control(loopStart)
         loopEnd = ticks_us()
         #print("------------------------LOOPEND:", loopEnd)
         if PRINT_DEBUG_LOOP:
             print("%ld" % (loopStart - oldLoopStart))
         oldLoopStart = loopStart
         makeup_time = desired_loop_time - ticks_diff(loopEnd, loopStart)
         if makeup_time > 0:
             sleep_us(makeup_time)
         else:
             print("Slow loop, took:",
                   (PROG_LOOP_TIME - makeup_time) / 1000,
                   "ms (ideal loop time:", PROG_LOOP_TIME / 1000, ")")
             #print("Slow loop, exceeded looptime by:", -1 * makeup_time / 1000, "ms (ideal loop time:", PROG_LOOP_TIME/1000, ")")
         #sleep_us(PROG_LOOP_TIME - ticks_diff(loopEnd, loopStart))
         if sysname == 'linux' or sysname == 'win32':
             #print("Simulation loopstart time:", loopStart, "us", "Uptime:", (loopStart - t0)/1e6)
             pass
Exemplo n.º 18
0
    def sendMessage(self, data,size = 32):
        reg = [0b10100000]

        
        
        self.csnLow()
        self.spi.write(bytearray([0b11100001]))
        self.csnHigh()
        
        self.csnLow()
        self.spi.write(bytearray(reg))
        
        localData = bytearray(data)
        localData.extend(bytearray(size - len(localData)))
        
        self.spi.write(bytearray(localData))
        
        self.csnHigh()
        
        self.ceHigh()
        utime.sleep_us(10)
        for i in range(0,10000):
            reg = self.readReg(7)[0]
            if reg & 0b00110000:
                break
        self.ceLow()
        self.writeReg(7,0b00110000) # Clear status flags.
def run_sensor(temp):
    # Make sure output is low
    trigger.value(0)
    utime.sleep_us(10)

    # Trigger 8 cycle sonic burst by setting trigger to high for 10us
    trigger.value(1)
    utime.sleep_us(10)
    trigger.value(0)

    # Wait for pulse to start on input pin.
    while echo() == 0:
        pass
    start = utime.ticks_us()

    # Run until input pin changes to low.
    while echo() == 1:
        pass
    finish = utime.ticks_us()

    utime.sleep_ms(10)

    # MCP9700A temperature sensor
    # T_A = temp.readTemp(analog_pin)

    if(isinstance(temp, str) == False):
        speed_sound = (331.4 + 0.6 * temp) * 0.0001        # cm/us
    else:
        speed_sound = (331.4 + 0.6 * 14.5) * 0.0001        # cm/us
    # Calculate and print out distance measured.
    return ((utime.ticks_diff(finish, start)) * speed_sound)/2
Exemplo n.º 20
0
def continueWithDataCapture(i2cDev):
    # INITIALIZATION
    print("DEFAULT MODE:", getCurrentMode(i2cDev))
    i2c.write(i2cDev, mag3110.CTRL_REG1, 0x00)
    utime.sleep_us(500)
    i2c.write(i2cDev, mag3110.CTRL_REG2, 0x80)
    print("NEW MODE:", getCurrentMode(i2cDev))

    utime.sleep_us(500)
    setOffset(i2cDev, mag3110.OFF_X_MSB, mag3110.OFF_X_LSB, 0)
    utime.sleep_us(500)
    setOffset(i2cDev, mag3110.OFF_Y_MSB, mag3110.OFF_Y_LSB, 0)
    utime.sleep_us(500)
    setOffset(i2cDev, mag3110.OFF_Z_MSB, mag3110.OFF_Z_LSB, 0)
    utime.sleep_us(500)
    i2c.write(i2cDev, mag3110.CTRL_REG1,
              ((i2c.read(i2cDev, mag3110.CTRL_REG1)[0])
               | mag3110.MAG3110_ACTIVE_MODE))
    utime.sleep(1)

    count = 1
    while (1 == 1):
        print(count, ":", readValues(i2cDev))
        count += 1
        utime.sleep(1)
Exemplo n.º 21
0
    def read_distance(self):

        self.motor_stop(LEFT_MOTOR)
        self.motor_stop(RIGHT_MOTOR)

        divider = 42
        maxtime = 250 * divider

        pin2.read_digital()
        pin1.write_digital(0)
        utime.sleep_us(2)
        pin1.write_digital(1)
        utime.sleep_us(10)
        pin1.write_digital(0)

        duration = machine.time_pulse_us(pin2, 1, maxtime)
        distance = duration / divider

        color = (0, 255, 0)

        if distance <= 35:
            color = (255, 0, 0)
        elif distance > 35 and distance < 50:
            color = (255, 128, 0)

        for led in range(4):
            self.np[led] = color

        self.np.show()

        return distance
Exemplo n.º 22
0
    def read_raw_data(self, result):
        """ Reads the raw (uncompensated) data from the sensor.

            Args:
                result: array of length 3 or alike where the result will be
                stored, in temperature, pressure, humidity order
            Returns:
                None
        """

        self._l1_barray[
            0] = self._mode_temperature << 5 | self._mode_pressure << 2 | BMP280_POWER_MODE_FORCED
        self.i2c.writeto_mem(self.address, BMP280_REGISTER_CONTROL,
                             self._l1_barray)

        time.sleep_us(self.compute_delay_time())  # Wait the required time

        # burst readout from 0xF7 to 0xFC, recommended by datasheet
        # we read the 6 bytes (3 bytes each)
        self.i2c.readfrom_mem_into(self.address, 0xF7, self._l8_barray)
        readout = self._l8_barray
        # pressure(0xF7): ((msb << 16) | (lsb << 8) | xlsb) >> 4
        raw_press = ((readout[0] << 16) | (readout[1] << 8) | readout[2]) >> 4
        # temperature(0xFA): ((msb << 16) | (lsb << 8) | xlsb) >> 4
        raw_temp = ((readout[3] << 16) | (readout[4] << 8) | readout[5]) >> 4

        result[0] = raw_temp
        result[1] = raw_press
Exemplo n.º 23
0
    def loop(self, base_t=1000, clockwise=True, limit=400):
        n = 0

        t = base_t
        cicle = 0

        while True:
            self.tick(n)

            if clockwise:
                n += 1
            else:
                n -= 1

            if n > 8:
                n = 0
                cicle += 1
            elif n < 0:
                n = 8
                cicle += 1

            if cicle > 10 and cicle % 10 == 0:
                if t > 4:
                    t = int(round(t * 0.9, 0))

                    if t < limit:
                        t = limit

            if cicle > 10000:
                cicle = 0

            if t > 0:
                utime.sleep_us(t)
Exemplo n.º 24
0
def test():
    """Bouncing box."""
    try:
        # Baud rate of 40000000 seems about the max
        spi = SPI(1, baudrate=40000000, sck=Pin(14), mosi=Pin(13))
        display = Display(spi, dc=Pin(4), cs=Pin(16), rst=Pin(17))
        display.clear()

        colors = [
            color565(255, 0, 0),
            color565(0, 255, 0),
            color565(0, 0, 255),
            color565(255, 255, 0),
            color565(0, 255, 255),
            color565(255, 0, 255)
        ]
        sizes = [12, 11, 10, 9, 8, 7]
        boxes = [Box(239, 319, sizes[i], display, colors[i]) for i in range(6)]

        while True:
            timer = ticks_us()
            for b in boxes:
                b.update_pos()
                b.draw()
            # Attempt to set framerate to 30 FPS
            timer_dif = 33333 - ticks_diff(ticks_us(), timer)
            if timer_dif > 0:
                sleep_us(timer_dif)

    except KeyboardInterrupt:
        display.cleanup()
Exemplo n.º 25
0
def test():
    """Bouncing box."""
    display=Display(spi,SPI_CS,SPI_DC)
    try:

        display.clear()

        colors = [color565(255, 0, 0),
                  color565(0, 255, 0),
                  color565(0, 0, 255),
                  color565(255, 255, 0),
                  color565(0, 255, 255),
                  color565(255, 0, 255)]
        sizes = [12, 11, 10, 9, 8, 7]
        boxes = [Box(128, 128, sizes[i], display,
                 colors[i]) for i in range(6)]

        while True:
            timer = ticks_us()
            for b in boxes:
                b.update_pos()
                b.draw()
            # Attempt to set framerate to 30 FPS
            timer_dif = 33333 - ticks_diff(ticks_us(), timer)
            if timer_dif > 0:
                sleep_us(timer_dif)

    except KeyboardInterrupt:
        display.cleanup()
Exemplo n.º 26
0
def measurement(avg):

    global echo
    global trig
    measurements = []
    for x in range(0,avg+1):
        trig.on()
        utime.sleep_us(10)
        trig.off()
        pulse_start=0
        pulse_end=0
        timeout = 10000
        while echo.value() is 0 and timeout > 0:
            pulse_start = utime.ticks_us()
            timeout -= 1

        timeout = 10000
        while echo.value() is 1 and timeout > 0:
            pulse_end = utime.ticks_us()
            timeout -=1
        if timeout > 0:
            pulse_duration = utime.ticks_diff(pulse_end,pulse_start)/(pow(10,6))
            distance = pulse_duration * 17150

            distance = round(distance, 2)
            measurements.append(distance)
        else:
            measurements.append(0)


    utime.sleep_us(10)
    return sum(measurements)/len(measurements)
Exemplo n.º 27
0
def CheckDistance():
    SpeedOfSoundInCM = 0.034

    # begin the LOW/HIGH/LOW trigger output sequence
    Trig.low()
    utime.sleep_us(2)
    Trig.high()
    utime.sleep_us(10)
    Trig.low()
    exitLoop = False
    loopcount = 0 #used as a failsafe if the signal doesn't return
    # now we wait for the Echo pin to go high
    while Echo.value() == 0 and exitLoop == False:
        loopcount = loopcount + 1
        delaytime = utime.ticks_us()
        # give up after 3,000 tries
        if loopcount > 3000 : exitLoop == True
    
    # we now a high if we did not timeout
    while Echo.value() == 1 and exitLoop == False:
        loopcount = loopcount + 1
        receivetime = utime.ticks_us()
        # give up after 3,000 tries
        if loopcount > 3000 : exitLoop == True
 
    if exitLoop == True: #We failed somewhere
        return 0
    else:
        distance = ((receivetime – delaytime) * SpeedOfSoundInCM) / 2
        return distance
Exemplo n.º 28
0
def _wait_(duration):
    global do_blinking
    while (duration > 0):
        utime.sleep_us(750)  # adapted by feeling. longer due to other cmds
        duration = duration - 1
        if (do_blinking == False):
            return
Exemplo n.º 29
0
def distance_measure():
    # trigger pulse LOW for 2us (just in case)
    trigger(0)
    utime.sleep_us(2)
    # trigger HIGH for a 10us pulse
    trigger(1)
    utime.sleep_us(10)
    trigger(0)
    # wait for the rising edge of the echo then start timer
    while echo() == 0:
        pass
    start = utime.ticks_us()
    # wait for end of echo pulse then stop timer
    while echo() == 1:
        pass
    finish = utime.ticks_us()
    # pause for 20ms to prevent overlapping echos
    utime.sleep_ms(20)
    # calculate distance by using time difference between start and stop
    # speed of sound 340m/s or .034cm/us. Time * .034cm/us = Distance sound travelled there and back
    # divide by two for distance to object detected.
    # Note: changing the multiplying factor to 0.0133858 for inches
    distance = ((utime.ticks_diff(start, finish)) * 0.0133858) / 2

    return distance * -1
Exemplo n.º 30
0
def make_payload():
    pycom.rgbled(blue)
    #distance = distance_median()
    count = pycom.nvs_get('dist')
    utime.sleep_us(100)
    #randomize water distance
    distance = os.urandom(1)[0]
    print("distance = {0} inches".format(distance))
    utime.sleep_ms(100)
    #subract 0.1V from battery voltage every 5 counts
    c = count
    v = pycom.nvs_get('v')
    if c % 5 == 0:
        v += 1
        pycom.nvs_set('v', v)
    print("v={0}".format(v))
    voltage = 4.0 - v * 0.1
    print("Measured Voltage: {0}V".format(voltage))
    #randomize flow rate
    x = os.urandom(1)[0]
    flow_rate = x % 4
    if (flow_rate < 3):
        print(flow_rate)
    else:
        flow_rate -= 1
        print(flow_rate)
    print("Flow Rate: {0}".format(flow_rate))
    #generate encoded packet to send to webapp
    full_packet = ustruct.pack('f', count) + ustruct.pack(
        'f', float(distance)) + ustruct.pack('f', voltage) + ustruct.pack(
            'f', float(flow_rate))
    return full_packet
Exemplo n.º 31
0
 def freq(self, freq=None):
     if freq is None:
         return int(25000000.0 / 4096 / (self._read(0xfe) - 0.5))
     prescale = int(25000000.0 / 4096.0 / freq + 0.5)
     old_mode = self._read(0x00) # Mode 1
     self._write(0x00, (old_mode & 0x7F) | 0x10) # Mode 1, sleep
     self._write(0xfe, prescale) # Prescale
     self._write(0x00, old_mode) # Mode 1
     utime.sleep_us(5)
     self._write(0x00, old_mode | 0xa1) # Mode 1, autoincrement on
Exemplo n.º 32
0
    def start_listening(self):
        self.reg_write(CONFIG, self.reg_read(CONFIG) | PWR_UP | PRIM_RX)
        self.reg_write(STATUS, RX_DR | TX_DS | MAX_RT)

        if self.pipe0_read_addr is not None:
            self.reg_write_bytes(RX_ADDR_P0, self.pipe0_read_addr)

        self.flush_rx()
        self.flush_tx()
        self.ce(1)
        utime.sleep_us(130)
Exemplo n.º 33
0
def main():
    # set internal clock
    rtc = settime(timezone_offset=TIMEZONE_OFFSET)
    year, month, day, hour, minute, second, *_ = rtc.now()

    trigger = Pin('GP5', mode=Pin.OUT)
    trigger.value(0)

    # initial trigger timer
    timer = Timer(3, mode=Timer.PERIODIC, width=32)
    timer_channel = timer.channel(Timer.A | Timer.B, period=30000000)
    timer_channel.irq(handler=lambda t: trigger.toggle(), trigger=Timer.TIMEOUT)

    try:
        while True:
            leds = clock2matrix(hour=hour, minute=minute).columns

            # led matrix multiplexing
            current_trigger = trigger.value()
            while trigger.value() == current_trigger:
                for col in leds:
                    latch.value(0)
                    # write current time
                    spi.write(col)
                    # update LEDs
                    latch.value(1)

                    sleep_ms(1)

                    latch.value(0)
                    spi.write(OFF)
                    latch.value(1)

                    sleep_us(50)

            latch.value(0)
            spi.write(OFF)
            latch.value(1)

            year, month, day, hour, minute, second, *_ = rtc.now()

            # update rtc at 04:00
            if hour == 4 and minute == 0:
                rtc = settime(timezone_offset=TIMEZONE_OFFSET)
    except Exception as e:
        matrix_off()
        while True:
            print(e)
            sleep_ms(2000)
Exemplo n.º 34
0
    def send_start(self, buf):
        # power up
        self.reg_write(CONFIG, (self.reg_read(CONFIG) | PWR_UP) & ~PRIM_RX)
        utime.sleep_us(150)
        # send the data
        self.cs(0)
        self.spi.readinto(self.buf, W_TX_PAYLOAD)
        self.spi.write(buf)
        if len(buf) < self.payload_size:
            self.spi.write(b'\x00' * (self.payload_size - len(buf))) # pad out data
        self.cs(1)

        # enable the chip so it can send the data
        self.ce(1)
        utime.sleep_us(15) # needs to be >10us
        self.ce(0)
Exemplo n.º 35
0
 def hal_pulse_enable(self):
     """Pulse the enable line high, and then low again."""
     self.enable_pin.value(0)
     sleep_us(1)
     self.enable_pin.value(1)
     sleep_us(1)       # Enable pulse needs to be > 450 nsec
     self.enable_pin.value(0)
     sleep_us(100)     # Commands need > 37us to settle
Exemplo n.º 36
0
def test():
    utime.sleep_us(10000)
Exemplo n.º 37
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)