Python pyb.delay() Examples

The following are 30 code examples of pyb.delay(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyb , or try the search function .
Example #1
Source File: accelleds.py    From micropython-stm-lib with MIT License 7 votes vote down vote up
def led_angle():
    # make LED objects
    l1 = pyb.LED(1)
    l2 = pyb.LED(2)
    accel = STAccel()

    while True:
        # get x-axis
        x = accel.x() * 50

        # turn on LEDs depending on angle
        if x < -10:
            l2.on()
            l1.off()
        elif x > 10:
            l1.on()
            l2.off()
        else:
            l1.off()
            l2.off()

        # delay so that loop runs at at 1/50ms = 20Hz
        pyb.delay(50) 
Example #2
Source File: mutex_test.py    From micropython-samples with MIT License 7 votes vote down vote up
def main():
    global var1, var2
    var1, var2 = 0, 0
    t2 = pyb.Timer(2, freq = 995, callback = update)
    t4 = pyb.Timer(4, freq = 1000, callback = update)
    for x in range(1000000):
        with mutex:             # critical section start
            a = var1
            pyb.udelay(200)
            b = var2
            result = a == b     # critical section end
        if not result:
            print('Fail after {} iterations'.format(x))
            break
        pyb.delay(1)
        if x % 1000 == 0:
            print(x)
    t2.deinit()
    t4.deinit()
    print(var1, var2) 
Example #3
Source File: irqtest.py    From micropython-mpu9x50 with MIT License 6 votes vote down vote up
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 #4
Source File: DHT22.py    From uPython-DHT22 with MIT License 6 votes vote down vote up
def do_measurement():
    global nc
    global gnd
    global vcc
    global data
    global micros
    global timer
    global index
    # Send the START signal
    data.init(Pin.OUT_PP)
    data.low()
    micros.counter(0)
    while micros.counter() < 25000:
        pass
    data.high()
    micros.counter(0)
    while micros.counter() < 20:
        pass
    # Activate reading on the data pin
    index = 0
    data.init(Pin.IN, Pin.PULL_UP)
    # Till 5mS the measurement must be over
    pyb.delay(5)

# Parse the data read from the sensor 
Example #5
Source File: epd.py    From micropython-epaper with Apache License 2.0 6 votes vote down vote up
def _power_off(self):                       # turn of power and all signals
        self.Pin_PANEL_ON.low()
#        self._SPI_send(b'\x00\x00')
        self.spi.deinit()
        self.Pin_SCK.init(mode = pyb.Pin.OUT_PP)
        self.Pin_SCK.low()
        self.Pin_MOSI.init(mode = pyb.Pin.OUT_PP)
        self.Pin_MOSI.low()
        self.Pin_BORDER.low()
        # ensure SPI MOSI and CLOCK are Low before CS Low
        self.Pin_RESET.low()
        self.Pin_EPD_CS.low()
        # pulse discharge pin
        self.Pin_DISCHARGE.high()
        pyb.delay(150)
        self.Pin_DISCHARGE.low()

# One frame of data is the number of lines * rows. For example:
# The 2.7” frame of data is 176 lines * 264 dots. 
Example #6
Source File: epdpart.py    From micropython-epaper with Apache License 2.0 6 votes vote down vote up
def _power_off(self):                       # turn of power and all signals
        self.Pin_RESET.low()
        self.Pin_PANEL_ON.low()
        self.Pin_BORDER.low()
        self.spi.deinit()
        self.Pin_SCK.init(mode = pyb.Pin.OUT_PP)
        self.Pin_SCK.low()
        self.Pin_MOSI.init(mode = pyb.Pin.OUT_PP)
        self.Pin_MOSI.low()
        # ensure SPI MOSI and CLOCK are Low before CS Low
        self.Pin_EPD_CS.low()
        # pulse discharge pin
        self.Pin_DISCHARGE.high()
        pyb.delay(150)
        self.Pin_DISCHARGE.low()

# USER INTERFACE
# clear_screen() calls clear_data() and, if show, EPD_clear()
# showdata() called from show() 
Example #7
Source File: pin_test.py    From upy-examples with MIT License 5 votes vote down vote up
def test_pin(pin_name):
    pin = pyb.Pin(pin_name, pyb.Pin.OUT_PP)
    pin.high()
    pyb.delay(250)
    pin.low()
    pyb.delay(250) 
Example #8
Source File: accelmouse.py    From micropython-stm-lib with MIT License 5 votes vote down vote up
def main():
    sw_state = False
    led = pyb.LED(1)
    switch = pyb.Switch()
    switch.callback(set_sw_state)
    accel = STAccel()
    hid = pyb.USB_HID()

    while True:
        if sw_state:
            x, y, z = accel.xyz()
            hid.send((0, int(x * MAG), int(-y * MAG), 0))

        pyb.delay(int(1000 / FREQ)) 
Example #9
Source File: Tach.py    From upy-examples with MIT License 5 votes vote down vote up
def test():
    """Test program - assumes X2 is jumpered to X1."""
    micropython.alloc_emergency_exception_buf(100)

    print("Starting tach")
    tach = Tachometer(timer_num=2, channel_num=1, pin_name='X1')

    print("Starting pulses")
    t5 = pyb.Timer(5, freq=4)
    oc_pin = pyb.Pin.board.X2
    oc = t5.channel(2, pyb.Timer.OC_TOGGLE, pin=oc_pin)

    for freq in range(0, 600, 100):
        if freq == 0:
            freq = 1
        else:
            t5.freq(freq * 4)   # x 2 for toggle, x2 for 2 pulses_per_rev
        pyb.delay(1000)
        print("RPM =",  tach.rpm(), "Freq =", freq, " as RPM =", freq * 60)

    # stop the pulses
    print("Stopping pulses")
    oc_pin.init(pyb.Pin.OUT_PP)
    # wait for 1.5 seconds
    pyb.delay(1500)
    print("RPM =",  tach.rpm())
    print("RPM =",  tach.rpm())

    print("Starting pulses again")
    # start the pulses up again
    oc = t5.channel(2, pyb.Timer.OC_TOGGLE, pin=oc_pin)
    pyb.delay(2000)
    print("RPM =",  tach.rpm())
    print("RPM =",  tach.rpm()) 
Example #10
Source File: pin_test_teensy.py    From upy-examples with MIT License 5 votes vote down vote up
def test_pin(pin_name):
    pin = pyb.Pin(pin_name, pyb.Pin.OUT_PP)
    pin.high()
    pyb.delay(250)
    pin.low()
    pyb.delay(250) 
Example #11
Source File: micropower.py    From micropython-epaper with Apache License 2.0 5 votes vote down vote up
def power_up(self):
        self.upcount += 1                       # Cope with nested calls
        if self.upcount == 1:
            if self.ah is not None:
                self.ah.high()                  # Enable I2C pullups
            if self.al is not None:
                self.al.low()                   # Power up
            pyb.delay(10)                       # Nominal time for device to settle 
Example #12
Source File: epd.py    From micropython-epaper with Apache License 2.0 5 votes vote down vote up
def __exit__(self, *_):
        self._nothing_frame()
        self._dummy_line()

        self.Pin_BORDER.low()
        pyb.delay(200)
        self.Pin_BORDER.high()

        # check DC/DC
        self._SPI_send(b'\x70\x0f')
        dc_state = self._SPI_read(b'\x73\x00') & 0x40
        if dc_state != 0x40:
            self.status = EPD_DC_FAILED
            self._power_off()
            raise EPDException("EPD DC power failure")
        self._SPI_send(b'\x70\x0B') # Conform with datasheet
        self._SPI_send(b'\x72\x00')
        # latch reset turn on
        self._SPI_send(b'\x70\x03')
        self._SPI_send(b'\x72\x01')
        # output enable off
#        self._SPI_send(b'\x70\x02') Conform with datasheet
#        self._SPI_send(b'\x72\x05')
        # power off charge pump Vcom
        self._SPI_send(b'\x70\x05')
        self._SPI_send(b'\x72\x03')
        # power off charge pump neg voltage
        self._SPI_send(b'\x70\x05')
        self._SPI_send(b'\x72\x01')
        pyb.delay(120)
        # discharge internal on
        self._SPI_send(b'\x70\x04')
        self._SPI_send(b'\x72\x80')
        # power off all charge pumps
        self._SPI_send(b'\x70\x05')
        self._SPI_send(b'\x72\x00')
        # turn of osc
        self._SPI_send(b'\x70\x07')
        self._SPI_send(b'\x72\x01')
        pyb.delay(50)
        self._power_off() 
Example #13
Source File: epdpart.py    From micropython-epaper with Apache License 2.0 5 votes vote down vote up
def exit(self, *_):
        self._nothing_frame()
        self._dummy_line()
        pyb.delay(25)
        self.Pin_BORDER.low()
        pyb.delay(200)
        self.Pin_BORDER.high()

        self._SPI_send(b'\x70\x0B') # Conform with datasheet
        self._SPI_send(b'\x72\x00')
        # latch reset turn on
        self._SPI_send(b'\x70\x03')
        self._SPI_send(b'\x72\x01')
        # power off charge pump Vcom
        self._SPI_send(b'\x70\x05')
        self._SPI_send(b'\x72\x03')
        # power off charge pump neg voltage
        self._SPI_send(b'\x70\x05')
        self._SPI_send(b'\x72\x01')
        pyb.delay(120)
        # discharge internal on
        self._SPI_send(b'\x70\x04')
        self._SPI_send(b'\x72\x80')
        # power off all charge pumps
        self._SPI_send(b'\x70\x05')
        self._SPI_send(b'\x72\x00')
        # turn of osc
        self._SPI_send(b'\x70\x07')
        self._SPI_send(b'\x72\x01')
        pyb.delay(50)
        self._power_off() 
Example #14
Source File: ssd1306.py    From micropython-drivers with MIT License 5 votes vote down vote up
def poweron(self):
    if self.offset == 1:
      pyb.delay(10)
    else:
      self.res.high()
      pyb.delay(1)
      self.res.low()
      pyb.delay(10)
      self.res.high()
      pyb.delay(10) 
Example #15
Source File: DHT11.py    From Smart-IoT-Planting-System with MIT License 5 votes vote down vote up
def __init__(self,pin_):
        self.PinName=pin_
        time.sleep(1)
        self.gpio_pin = Pin(pin_, Pin.OUT_PP)
#        pyb.delay(10) 
Example #16
Source File: upcd8544.py    From Smart-IoT-Planting-System with MIT License 5 votes vote down vote up
def sleep_ms(self, mseconds):
        try:
            time.sleep_ms(mseconds)
        except AttributeError:
            machine.delay(mseconds) 
Example #17
Source File: touch_bytecode.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def touch_parameter(self, confidence = 5, margin = 50, delay = 10, calibration = None):
        if not self.asynchronous: # Ignore attempts to change on the fly.
            confidence = max(min(confidence, 25), 5)
            if confidence != self.buf_length:
                self.buff = [[0,0] for x in range(confidence)]
                self.buf_length = confidence
            self.delay = max(min(delay, 100), 5)
            margin = max(min(margin, 100), 1)
            self.margin = margin * margin # store the square value
            if calibration:
                self.calibration = calibration

# get_touch(): Synchronous use. get a touch value; Parameters:
#
# initital: Wait for a non-touch state before getting a sample. 
#           True = Initial wait for a non-touch state
#           False = Do not wait for a release
# wait: Wait for a touch or not?
#       False: Do not wait for a touch and return immediately
#       True: Wait until a touch is pressed. 
# raw: Setting whether raw touch coordinates (True) or normalized ones (False) are returned
#      setting the calibration vector to (0, 1, 0, 1, 0, 1, 0, 1) result in a identity mapping
# timeout: Longest time (ms, or None = 1 hr) to wait for a touch or release
#
# Return (x,y) or None
# 
Example #18
Source File: touch_bytecode.py    From micropython-tft-gui with MIT License 5 votes vote down vote up
def __init__(self, controller = "XPT2046", asyn = False, *, confidence = 5, margin = 50, delay = 10, calibration = None):
        if PCB_VERSION == 1:
            self.pin_clock = pyb.Pin("Y8", pyb.Pin.OUT_PP)
            self.pin_clock.value(0)
            self.pin_d_out = pyb.Pin("Y7", pyb.Pin.OUT_PP)
            self.pin_d_in  = pyb.Pin("Y6", pyb.Pin.IN)
            self.pin_irq   = pyb.Pin("Y5", pyb.Pin.IN)
        else:
            self.pin_clock = pyb.Pin("X11", pyb.Pin.OUT_PP)
            self.pin_clock.value(0)
            self.pin_d_out = pyb.Pin("X12", pyb.Pin.OUT_PP)
            self.pin_d_in  = pyb.Pin("Y1", pyb.Pin.IN)
            self.pin_irq   = pyb.Pin("Y2", pyb.Pin.IN)
# set default values
        self.ready = False
        self.touched = False
        self.x = 0
        self.y = 0
        self.buf_length = 0
        cal = TOUCH.DEFAULT_CAL if calibration is None else calibration
        self.asynchronous = False
        self.touch_parameter(confidence, margin, delay, cal)
        if asyn:
            self.asynchronous = True
            asyncio.create_task(self._main_thread())

# set parameters for get_touch()
# res: Resolution in bits of the returned values, default = 10
# confidence: confidence level - number of consecutive touches with a margin smaller than the given level
#       which the function will sample until it accepts it as a valid touch
# margin: Difference from mean centre at which touches are considered at the same position 
# delay: Delay between samples in ms.
# 
Example #19
Source File: lpf.py    From micropython-filters with MIT License 5 votes vote down vote up
def sine_sweep(start, end, mult):     # Emit sinewave on DAC1
    buf = bytearray(100)
    for i in range(len(buf)):
        buf[i] = 128 + int(110 * math.sin(2 * math.pi * i / len(buf)))

    freq = start
    while True:
        dac1.write_timed(buf, int(freq) * len(buf), mode=pyb.DAC.CIRCULAR)
        print(freq, "Hz")
        pyb.delay(2500)
        freq *= mult
        if freq > end:
            freq = start 
Example #20
Source File: osc.py    From micropython-filters with MIT License 5 votes vote down vote up
def sine_sweep(start, end, mult):     # Emit sinewave on DAC1
    buf = bytearray(100)
    for i in range(len(buf)):
        buf[i] = 128 + int(110 * math.sin(2 * math.pi * i / len(buf)))

    freq = start
    while True:
        dac1.write_timed(buf, int(freq) * len(buf), mode=pyb.DAC.CIRCULAR)
        print(freq, "Hz")
        pyb.delay(2500)
        freq *= mult
        if freq > end:
            freq = start 
Example #21
Source File: sim800l.py    From micropython-upyphone with MIT License 5 votes vote down vote up
def sms_alert(self):
        self.command('AT+CALS=1,1\n')  # set ringtone
        pyb.delay(3000)
        self.command('AT+CALS=3,0\n')  # set ringtone 
Example #22
Source File: sim800l.py    From micropython-upyphone with MIT License 5 votes vote down vote up
def wakechars(self):
        self._uart.write('AT\n')        # will be ignored
        pyb.delay(100) 
Example #23
Source File: sim800l.py    From micropython-upyphone with MIT License 5 votes vote down vote up
def command(self, cmdstr, lines=1, waitfor=500, msgtext=None):
        #flush input
        #print(cmdstr)
        while self._uart.any():
            self._uart.readchar()
        self._uart.write(cmdstr)
        if msgtext:
            self._uart.write(msgtext)
        if waitfor>1000:
            pyb.delay(waitfor-1000)
        buf=self._uart.readline() #discard linefeed etc
        #print(buf)
        buf=self._uart.readline()
        #print(buf)
        if not buf:
            return None
        result = convert_to_string(buf)
        if lines>1:
            self.savbuf = ''
            for i in range(lines-1):
                buf=self._uart.readline()
                if not buf:
                    return result
                #print(buf)
                buf = convert_to_string(buf)
                if not buf == '' and not buf == 'OK':
                    self.savbuf += buf+'\n'
        return result 
Example #24
Source File: wdog.py    From micropython-samples with MIT License 5 votes vote down vote up
def test():
    led = pyb.LED(2)
    led1 = pyb.LED(3)
    dog = wdog()
    dog.start(1000)
    for x in range(10):
        led.toggle()
        pyb.delay(500)
        dog.feed()
    dog.start(4000)
    for x in range(20):
        led1.toggle()
        pyb.delay(500) 
Example #25
Source File: magtest.py    From micropython-mpu9x50 with MIT License 5 votes vote down vote up
def test():
    mpu9150 = MPU9150('X')
    testfunc(mpu9150)
    print()
    pyb.delay(250)
    print("Repeating")
    testfunc(mpu9150) 
Example #26
Source File: lcdshield.py    From micropython-stm-lib with MIT License 5 votes vote down vote up
def main():
    lcd = STM_LCDShield()

    lcd.write("ABCDEFGHIJKLMNOP")         # Send a string
    lcd.write("1234567890123456", row=1)  # Second line

    pyb.delay(3000) # 3 second delay
    lcd.clear()
    pyb.delay(500)

    # Send some more
    lcd.write("Hello, PyCologne")
    lcd.write("from MicroPython", row=1) 
Example #27
Source File: accelusbmidi.py    From micropython-stm-lib with MIT License 5 votes vote down vote up
def main():
    import pyb

    serial = pyb.USB_VCP()
    midi = MidiOut(serial, channel=1)
    switch = pyb.Switch()

    if hasattr(pyb, 'Accel'):
        accel = pyb.Accel()
        SCALE = 1.27
    else:
        from staccel import STAccel
        accel = STAccel()
        SCALE = 127

    while True:
        while not switch():
            pyb.delay(10)

        note = abs(int(accel.x() * SCALE))
        velocity = abs(int(accel.y() * SCALE))
        midi.note_on(note, velocity)

        while switch():
            pyb.delay(50)

        midi.note_off(note) 
Example #28
Source File: lcdmidimonitor.py    From micropython-stm-lib with MIT License 5 votes vote down vote up
def main():
    serial = pyb.UART(2, BAUDRATE)
    lcd = STM_LCDShield()
    monitor = MidiMonitor(lcd)
    midiin = MidiIn(serial, monitor, debug=True)
    lcd.write("MIDI Mon ")
    pyb.delay(1000)
    lcd.write("ready")
    pyb.delay(1000)
    lcd.write("     ", col=9)

    while True:
        midiin.poll()
        pyb.delay(POLL_INTERVAL) 
Example #29
Source File: touch_bytecode.py    From micropython-tft-gui with MIT License 4 votes vote down vote up
def get_touch(self, initial = True, wait = True, raw = False, timeout = None):
        if self.asynchronous:
            return None # Should only be called in synhronous mode
        if timeout == None: 
            timeout = 3600000 # set timeout to 1 hour
# 
        if initial:  ## wait for a non-touch state
            sample = True
            while sample and timeout > 0:
                sample = self.raw_touch()
                pyb.delay(self.delay)
                timeout -= self.delay
            if timeout <= 0: # after timeout, return None
                return None
#
        buff = self.buff
        buf_length = self.buf_length
        buffptr = 0
        nsamples = 0
        while timeout > 0:
            if nsamples == buf_length:
                meanx = sum([c[0] for c in buff]) // buf_length
                meany = sum([c[1] for c in buff]) // buf_length
                dev = sum([(c[0] - meanx)**2 + (c[1] - meany)**2 for c in buff]) / buf_length
                if dev <= self.margin: # got one; compare against the square value
                    if raw:
                        return (meanx, meany)
                    else: 
                        return self.do_normalize((meanx, meany))
# get a new value 
            sample = self.raw_touch()  # get a touch
            if sample == None:
                if not wait:
                    return None
                nsamples = 0    # Invalidate buff
            else:
                buff[buffptr] = sample # put in buff
                buffptr = (buffptr + 1) % buf_length
                nsamples = min(nsamples +1, buf_length)
            pyb.delay(self.delay)
            timeout -= self.delay
        return None

# Asynchronous use: this thread maintains self.x and self.y 
Example #30
Source File: touch_bytecode.py    From micropython-tft-gui with MIT License 4 votes vote down vote up
def touch_talk(self, cmd, bits):

        global CONTROL_PORT
        gpio_bsr = CONTROL_PORT + stm.GPIO_BSRRL
        gpio_idr = CONTROL_PORT + stm.GPIO_IDR
#
# now shift the command out, which is 8 bits 
# data is sampled at the low-> high transient
#
        stm.mem16[gpio_bsr + 2] = T_CLOCK # Empty clock cycle before start, maybe obsolete
        mask = 0x80  # high bit first
        for i in range(8):
            stm.mem16[gpio_bsr + 2] = T_CLOCK # set clock low in the beginning
            if cmd & mask:
                stm.mem16[gpio_bsr + 0] = T_DOUT # set data bit high
            else:
                stm.mem16[gpio_bsr + 2] = T_DOUT # set data bit low
            for i in range(1): pass #delay
            stm.mem16[gpio_bsr + 0] = T_CLOCK # set clock high
            mask >>= 1
        stm.mem16[gpio_bsr + 2] = T_CLOCK | T_DOUT# Another clock & data, low
        stm.mem16[gpio_bsr + 0] = T_CLOCK # clock High
#
# now shift the data in, which is 8 or 12 bits 
# data is sampled after the high->low transient
#
        result = 0
        for i in range(bits):
            stm.mem16[gpio_bsr + 2] = T_CLOCK # Clock low
            if stm.mem16[gpio_idr + 0] & T_DIN: # get data
                bit = 1
            else:
                bit = 0
            result = (result << 1) | bit # shift data in
            stm.mem16[gpio_bsr + 0] = T_CLOCK # Clock high
#
# another clock cycle, maybe obsolete
#
        stm.mem16[gpio_bsr + 2] = T_CLOCK # Another clock toggle, low
        stm.mem16[gpio_bsr + 0] = T_CLOCK # clock High
        stm.mem16[gpio_bsr + 2] = T_CLOCK # Clock low
# now we're ready to leave
        return result