Python time.sleep_ms() Examples

The following are 30 code examples of time.sleep_ms(). 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 time , or try the search function .
Example #1
Source File: mpu6050.py    From py-mpu6050 with GNU General Public License v3.0 6 votes vote down vote up
def get_sensor_avg(self, samples, softstart=100):
        '''Return the average readings from the sensors over the
        given number of samples.  Discard the first softstart
        samples to give things time to settle.'''
        sample = self.read_sensors()
        counters = [0] * 7

        for i in range(samples + softstart):
            # the sleep here is to ensure we read a new sample
            # each time
            time.sleep_ms(2)

            sample = self.read_sensors()
            if i < softstart:
                continue

            for j, val in enumerate(sample):
                counters[j] += val

        return [x//samples for x in counters] 
Example #2
Source File: speak.py    From UIFlow-Code with GNU General Public License v3.0 6 votes vote down vote up
def tone(self, freq=1800, duration=200, volume=None, timer=True):
    duration = min(max(30, duration), 2000)
    freq = min(max(20, freq), 20000)
    self.checkInit()
    if volume == None:
      self.pwm.init(freq=freq, duty=self._volume)
    else:
      self.pwm.init(freq=freq, duty=volume)
    if timer:
      # if self._timer.isrunning():
      #   self._timer.period(duration)
      # else:
      self._timer.init(period=duration, mode=self._timer.ONE_SHOT, callback=self._timeout_cb)   
      time.sleep_ms(duration-15)
    else:
      time.sleep_ms(duration)
      self.pwm.duty(0)
      time.sleep_ms(1)
      self.pwm.freq(1) 
Example #3
Source File: demo_net_socket.py    From MaixPy_scripts with MIT License 6 votes vote down vote up
def wifi_reset():
        global uart
        wifi_enable(0)
        time.sleep_ms(200)
        wifi_enable(1)
        time.sleep(2)
        uart = UART(UART.UART2,115200,timeout=1000, read_buf_len=4096)
        tmp = uart.read()
        uart.write("AT+UART_CUR=921600,8,1,0,0\r\n")
        print(uart.read())
        uart = UART(UART.UART2,921600,timeout=1000, read_buf_len=10240) # important! baudrate too low or read_buf_len too small will loose data
        uart.write("AT\r\n")
        tmp = uart.read()
        print(tmp)
        if not tmp.endswith("OK\r\n"):
            print("reset fail")
            return None
        try:
            nic = network.ESP8285(uart)
        except Exception:
            return None
        return nic 
Example #4
Source File: demo_send_pic.py    From MaixPy_scripts with MIT License 6 votes vote down vote up
def wifi_reset():
    global uart
    wifi_enable(0)
    time.sleep_ms(200)
    wifi_enable(1)
    time.sleep(2)
    uart = UART(UART.UART2,115200,timeout=1000, read_buf_len=4096)
    tmp = uart.read()
    uart.write("AT+UART_CUR=921600,8,1,0,0\r\n")
    print(uart.read())
    uart = UART(UART.UART2,921600,timeout=1000, read_buf_len=4096)
    uart.write("AT\r\n")
    tmp = uart.read()
    print(tmp)
    if not tmp.endswith("OK\r\n"):
        print("reset fail")
        return None
    try:
        nic = network.ESP8285(uart)
    except Exception:
        return None
    return nic 
Example #5
Source File: upgrade_at_firmware.py    From MaixPy_scripts with MIT License 6 votes vote down vote up
def wait_upgrade(self):
        print("[wait upgrade process]")
        read = b""
        tim = time.ticks_ms()
        while 1:
            if time.ticks_ms() - tim > 80000:
                raise Exception("wait for update timeout")
            recv = self.uart.read()
            if recv:
                print(recv)
            else:
                print(".", end='')
            if recv:
                read += recv
            if self.update_step != 4 and b"+CIPUPDATE:4" in read:
                self.update_step = 4
            if self.update_step == 4 and b"OK" in read:
                break
            time.sleep_ms(200) 
Example #6
Source File: backup.py    From terkin-datalogger with GNU Affero General Public License v3.0 6 votes vote down vote up
def rename_file(self, oldfile, newfile):
        """
        Rename fila

        :param oldfile: old file name
        :param newfile: new file name

        """
        #log.info('Renaming backup file {} to {}'.format(oldfile, newfile))
        try:
            os.rename(oldfile, newfile)
        except OSError:
            pass
        time.sleep_ms(5)
        uos.sync()
        time.sleep_ms(5) 
Example #7
Source File: main.py    From microhomie with MIT License 6 votes vote down vote up
def read_temp(self, fahrenheit=True):
        """
        Reads temperature from a single DS18X20
        :param fahrenheit: Whether or not to return value in Fahrenheit
        :type fahrenheit: bool
        :return: Temperature
        :rtype: float
        """
        self.ds18b20.convert_temp()
        time.sleep_ms(750)
        temp = self.ds18b20.read_temp(self.addr)
        if fahrenheit:
            ntemp = temp
            print("Temp: " + str(self.c_to_f(ntemp)))
            return self.c_to_f(ntemp)
        return temp 
Example #8
Source File: upgrade_at_firmware.py    From MaixPy_scripts with MIT License 6 votes vote down vote up
def wait_join_ap(self):
        print("[wait join ap]")
        read = b""
        tim = time.ticks_ms()
        while 1:
            if time.ticks_ms() - tim > 10000:
                raise Exception("wait for join AP timeout")
            recv = self.uart.read()
            if recv:
                print(recv)
            else:
                print(".", end='')
            if recv:
                read += recv
            if b"GOT IP" in read:
                break
        time.sleep_ms(1000)
        read = self.uart.read()
        print(read) 
Example #9
Source File: upgrade_at_firmware.py    From MaixPy_scripts with MIT License 6 votes vote down vote up
def cmd_join_ap_and_wait(self):
        print("[cmd join ap]")
        recv = self.uart.read()
        print(recv)
        if self.passwd:
            self.uart.write(b'AT+CWJAP_DEF="{}","{}"\r\n'.format(self.ssid, self.passwd))
        else:
            self.uart.write(b'AT+CWJAP_DEF="{}"\r\n'.format(self.ssid))
        time.sleep_ms(200)
        print("[wait join ap -- 0]")
        read = b""
        tim = time.ticks_ms()
        while 1:
            if time.ticks_ms() - tim > 10000:
                return False
            recv = self.uart.read()
            if recv:
                print(recv)
            else:
                print(".", end='')
            if recv:
                read += recv
            if b"GOT IP" in read:
                return True 
Example #10
Source File: buzzer.py    From developer-badge-2018-apps with Apache License 2.0 6 votes vote down vote up
def playnotes(self, title, length=150, duty=64):
        if title not in self.notes:
          print('unknown title: {}'.format(title))
          return

        melody = self.notes[title]
        print('Play', title)
        for i in melody:
            if i == 0:
                self.pwm.duty(0)
            else:
                self.pwm.freq(i)
                self.pwm.duty(duty)
            time.sleep_ms(length)

        self.pwm.duty(0) 
Example #11
Source File: iot_client.py    From developer-badge-2018-apps with Apache License 2.0 6 votes vote down vote up
def main():
    c.set_callback(sub_cb)
    if not wait_network():
        print('Cannot connect WiFi')
        raise Exception('Cannot connect WiFi')

    c.connect()
    if conf.data['orgID'] != 'quickstart':
        c.subscribe(ledCommandTopic)
        c.subscribe(irCommandTopic)
    print('Connected, waiting for event ({})'.format(conf.data['deviceID']))

    status = {'d': {'sine':{}}}
    count = 0
    try:
        while True:
            status['d']['sine'] = sineVal(-1.0, 1.0, 16, count)
            count += 1
            c.publish(statusTopic, json.dumps(status))
            time.sleep_ms(10000)
            #c.wait_msg()
            c.check_msg()
    finally:
        c.disconnect()
        print('Disonnected') 
Example #12
Source File: buzzer.py    From developer-badge-2018-apps with Apache License 2.0 6 votes vote down vote up
def playnotes(self, title, length=150, duty=64):
        # Init
        p = Pin(27, Pin.OUT)
        self.pwm = PWM(p)
        self.pwm.duty(0)

        if title not in self.notes:
          print('unknown title: {}'.format(title))
          return

        melody = self.notes[title]
        print('Play', title)
        for i in melody:
            if i == 0:
                self.pwm.duty(0)
            else:
                self.pwm.freq(i)
                self.pwm.duty(duty)
            time.sleep_ms(length)

        # deinit
        self.pwm.deinit() 
Example #13
Source File: am2320.py    From MicroPython-ESP8266-DHT-Nokia-5110 with MIT License 6 votes vote down vote up
def measure(self):
        buf = self.buf
        address = self.address
        # wake sensor
        try:
        	self.i2c.writeto(address, b'')
        except OSError:
        	pass
        # read 4 registers starting at offset 0x00
        self.i2c.writeto(address, b'\x03\x00\x04')
        # wait at least 1.5ms
        time.sleep_ms(2)
        # read data
        self.i2c.readfrom_mem_into(address, 0, buf)
        # debug print
        print(ustruct.unpack('BBBBBBBB', buf))
        crc = ustruct.unpack('<H', bytearray(buf[-2:]))[0]
        if (crc != self.crc16(buf[:-2])):
            raise Exception("checksum error") 
Example #14
Source File: demo_http.py    From MaixPy_scripts with MIT License 6 votes vote down vote up
def wifi_reset():
    global uart
    wifi_enable(0)
    time.sleep_ms(200)
    wifi_enable(1)
    time.sleep(2)
    uart = UART(UART.UART2,115200,timeout=1000, read_buf_len=4096)
    tmp = uart.read()
    uart.write("AT+UART_CUR=921600,8,1,0,0\r\n")
    print(uart.read())
    uart = UART(UART.UART2,921600,timeout=1000, read_buf_len=10240) # important! baudrate too low or read_buf_len too small will loose data
    uart.write("AT\r\n")
    tmp = uart.read()
    print(tmp)
    if not tmp.endswith("OK\r\n"):
        print("reset fail")
        return None
    try:
        nic = network.ESP8285(uart)
    except Exception:
        return None
    return nic 
Example #15
Source File: ssd1306.py    From tinypico-micropython with MIT License 6 votes vote down vote up
def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):
        self.rate = 10 * 1024 * 1024
        dc.init(dc.OUT, value=0)
        res.init(res.OUT, value=0)
        cs.init(cs.OUT, value=1)
        self.spi = spi
        self.dc = dc
        self.res = res
        self.cs = cs
        import time
        self.res(1)
        time.sleep_ms(1)
        self.res(0)
        time.sleep_ms(10)
        self.res(1)
        super().__init__(width, height, external_vcc) 
Example #16
Source File: sht30.py    From micropython-sht30 with Apache License 2.0 6 votes vote down vote up
def send_cmd(self, cmd_request, response_size=6, read_delay_ms=100):
        """
        Send a command to the sensor and read (optionally) the response
        The responsed data is validated by CRC
        """
        try:
            self.i2c.start(); 
            self.i2c.writeto(self.i2c_addr, cmd_request); 
            if not response_size:
                self.i2c.stop(); 	
                return
            time.sleep_ms(read_delay_ms)
            data = self.i2c.readfrom(self.i2c_addr, response_size) 
            self.i2c.stop(); 
            for i in range(response_size//3):
                if not self._check_crc(data[i*3:(i+1)*3]): # pos 2 and 5 are CRC
                    raise SHT30Error(SHT30Error.CRC_ERROR)
            if data == bytearray(response_size):
                raise SHT30Error(SHT30Error.DATA_ERROR)
            return data
        except OSError as ex:
            if 'I2C' in ex.args[0]:
                raise SHT30Error(SHT30Error.BUS_ERROR)
            raise ex 
Example #17
Source File: weather.py    From ulnoiot-upy with MIT License 6 votes vote down vote up
def loop():
    show_temp = True
    while True:
        g = get()
        display.fill(0)
        display.text("Weather in", 0, 0)
        display.text(g['name'], 0, 8)
        if left_button.value() == 0 or right_button.value() == 0:
            show_temp = not show_temp
        if show_temp:
            celsius = g['main']['temp'] - 273.15
            display.text("Temp/C: %.1f" % celsius, 0, 24)
            display.text("Temp/F: %.1f" % (celsius * 1.8 + 32), 0, 32)
        else:  # humidity
            display.text("Humidity: %d%%" % g['main']['humidity'], 0, 24)
        if lower_button.value() == 0:
            break
        display.show()
        time.sleep_ms(500) 
Example #18
Source File: buzzer.py    From developer-badge-2018-apps with Apache License 2.0 6 votes vote down vote up
def playnotes(self, title, length=150, duty=64):
        if title not in self.notes:
          print('unknown title: {}'.format(title))
          return

        melody = self.notes[title]
        print('Play', title)
        for i in melody:
            if i == 0:
                self.pwm.duty(0)
            else:
                self.pwm.freq(i)
                self.pwm.duty(duty)
            time.sleep_ms(length)

        self.pwm.duty(0) 
Example #19
Source File: ds18x20_sensor.py    From terkin-datalogger with GNU Affero General Public License v3.0 6 votes vote down vote up
def read(self):
        """
        - Start conversion on all DS18x20 sensors.
        - Wait for conversion.
        - Read all DS18x20 sensors.
        """

        if self.bus is None or self.driver is None:
            return self.SENSOR_NOT_INITIALIZED

        log.info('Acquire readings from all DS18x20 sensors attached to bus "{}"'.format(self.bus.name))

        # Start conversion on all DS18x20 sensors.
        self.driver.convert_temp()
        time.sleep_ms(750)

        # Read scratch memory of each sensor.
        data = self.read_devices()

        if not data:
            log.warning('No data from any DS18x20 devices on bus "{}"'.format(self.bus.name))

        log.debug('Data from 1-Wire bus "{}" is "{}"'.format(self.bus.name, data))

        return data 
Example #20
Source File: upcd8544.py    From Smart-IoT-Planting-System with MIT License 5 votes vote down vote up
def power_off(self):
        self.clear()
        self.command([0x20, 0x08])
        # 0x20 - basic instruction set
        # 0x08 - set display to blank (doesn't delete contents)
        self.sleep_ms(10)
        if self.pwr:
            self.pwr.value(0) # turn off power 
Example #21
Source File: BMP180.py    From mpy-lib with MIT License 5 votes vote down vote up
def measure(self):
        self.setReg(0xF4, 0x2E)
        time.sleep_ms(5)
        self.UT = self.get2Reg(0xF6)
        self.setReg(0xF4, 0x34)
        time.sleep_ms(5)
        self.UP = self.get2Reg(0xF6)

    # get Temperature and Pressure 
Example #22
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 #23
Source File: mpu6050.py    From py-mpu6050 with GNU General Public License v3.0 5 votes vote down vote up
def wait_for_stable(self, numsamples=10):
        print('* waiting for gyros to stabilize')

        gc.collect()
        time_start = time.time()
        samples = []

        while True:
            now = time.time()
            if now - time_start > self.stable_reading_timeout:
                raise CalibrationFailure()

            # the sleep here is to ensure we read a new sample
            # each time
            time.sleep_ms(2)

            sample = self.read_sensors()
            samples.append(sample[4:7])
            if len(samples) < numsamples:
                continue

            samples = samples[-numsamples:]

            totals = [0] * 3
            for cola, colb in zip(samples, samples[1:]):
                deltas = [abs(a-b) for a,b in zip(cola, colb)]
                totals = [a+b for a,b in zip(deltas, totals)]

            avg = [a/numsamples for a in totals]

            if all(x < self.max_gyro_variance for x in avg):
                break

        now = time.time()
        print('* gyros stable after {:0.2f} seconds'.format(now-time_start)) 
Example #24
Source File: backup.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def write(self, buffer):
        """
        Remove oldest backup, rotate name and write buffer to file.

        :param buffer: buffer to write

        """
        if self.backup_count:

            # Remove the oldest backup file if it is there.
            old_backupfile = "{}.{}".format(self.filename, self.backup_count)
            #log.info('Removing backup file {}'.format(old_backupfile))
            file_remove(old_backupfile)

            # Rename backup files in between oldest and newest one.
            for i in range(self.backup_count - 1, 0, -1):
                if i < self.backup_count:
                    self.rename_file(
                        "{}.{}".format(self.filename, i),
                        "{}.{}".format(self.filename, i + 1))

            # Rename most recent backup file.
            self.rename_file(self.filename, "{}.{}".format(self.filename, 1))

        # Write new most recent backup file.
        log.info('Writing recent backup to {}'.format(self.filename))
        with open(self.filename, "w") as outfile:
            #log.info('copyfileobj: {} => {}'.format(buffer, outfile))
            copyfileobj(buffer, outfile)

        time.sleep_ms(150)
        uos.sync() 
Example #25
Source File: Eve.py    From spidriver with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def screenshot(self, dest):
        REG_SCREENSHOT_EN = 0x302010  # Set to enable screenshot mode
        REG_SCREENSHOT_Y = 0x302014  # Y line register
        REG_SCREENSHOT_START = 0x302018  # Screenshot start trigger
        REG_SCREENSHOT_BUSY = 0x3020e8  # Screenshot ready flags
        REG_SCREENSHOT_READ = 0x302174  # Set to enable readout
        RAM_SCREENSHOT = 0x3c2000  # Screenshot readout buffer

        self.finish()
        self.unstream()
        w = self.raw_read(self.REG_HSIZE)
        h = self.raw_read(self.REG_VSIZE)

        f = open(dest, "wb")
        f.write(bytes("P6\n%d %d\n255\n" % (w, h), "utf-8"))
        self.wr32(REG_SCREENSHOT_EN, 1)
        self.wr32(0x0030201c, 32)

        for ly in range(h):
            print("line %d" % ly)
            self.wr32(REG_SCREENSHOT_Y, ly)
            self.wr32(REG_SCREENSHOT_START, 1)
            time.sleep_ms(2)
            while self.raw_read(REG_SCREENSHOT_BUSY) | self.raw_read(REG_SCREENSHOT_BUSY + 4):
                pass
            self.wr32(REG_SCREENSHOT_READ, 1)
            bgra = self.rd(RAM_SCREENSHOT, 4 * w)
            (b, g, r, a) = [bgra[i::4] for i in range(4)]
            f.write(bytes(sum(zip(r, g, b), ())))
            self.wr32(REG_SCREENSHOT_READ, 0)
        self.wr32(REG_SCREENSHOT_EN, 0)
        f.close()
        self.stream() 
Example #26
Source File: wifi.py    From terkin-datalogger with GNU Affero General Public License v3.0 5 votes vote down vote up
def wait_for_connection(self, timeout=15.0):
        """
        Wait for network to arrive.

        :param timeout:  (Default value = 15.0)

        """

        # Set interval how often to poll for WiFi connectivity.
        network_poll_interval = 250

        # How many checks to make.
        checks = int(timeout / (network_poll_interval / 1000.0))

        self.stopwatch.reset()

        do_report = True
        while not self.is_connected():

            delta = self.stopwatch.elapsed()
            eta = timeout - delta

            if checks <= 0 or eta <= 0:
                break

            # Report about the progress each 3 seconds.
            if int(delta) % 3 == 0:
                if do_report:
                    log.info('WiFi STA: Waiting for network to come up within {} seconds'.format(eta))
                    do_report = False
            else:
                do_report = True

            # Save power while waiting.
            machine.idle()

            # Don't busy-wait.
            time.sleep_ms(network_poll_interval)

            checks -= 1 
Example #27
Source File: qr.py    From specter-diy with MIT License 5 votes vote down vote up
def query(self, data, timeout=100):
        """Blocking query"""
        self.uart.write(data)
        t0 = time.time()
        while self.uart.any() < 7:
            time.sleep_ms(10)
            t = time.time()
            if t > t0+timeout/1000:
                return None
        res = self.uart.read(7)
        return res 
Example #28
Source File: wifi_manager.py    From micropython-wifimanager with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def connect_to(cls, *, ssid, password, **kwargs) -> bool:
        cls.wlan().connect(ssid, password, **kwargs)

        for check in range(0, 10):  # Wait a maximum of 10 times (10 * 500ms = 5 seconds) for success
            if cls.wlan().isconnected():
                return True
            time.sleep_ms(500)
        return False 
Example #29
Source File: mpu6050.py    From py-mpu6050 with GNU General Public License v3.0 5 votes vote down vote up
def reset(self):
        print('* reset')
        self.write_byte(MPU6050_RA_PWR_MGMT_1, (
            (1 << MPU6050_PWR1_DEVICE_RESET_BIT)
        ))
        time.sleep_ms(100)

        self.write_byte(MPU6050_RA_SIGNAL_PATH_RESET, (
            (1 << MPU6050_PATHRESET_GYRO_RESET_BIT) |
            (1 << MPU6050_PATHRESET_ACCEL_RESET_BIT) |
            (1 << MPU6050_PATHRESET_TEMP_RESET_BIT)
        ))
        time.sleep_ms(100) 
Example #30
Source File: APDS9930.py    From mpy-lib with MIT License 5 votes vote down vote up
def Power(self, on=True):
        t = self.getReg(APDS9930_ENABLE)
        t &= 0xFE
        if on:
            t |= 1
        self.setReg(APDS9930_ENABLE, t)
        time.sleep_ms(3)