Example #1
0
def play_show(tune, pin=27, display=matrix.display, duration=None):
    from machine import Pin, PWM
    from utime import sleep_ms

    try:
        pwm = PWM(Pin(pin))
        if duration is None:
            set_default(tune[0])
        else:
            set_duration(duration)
        for tone in tune:
            tone = tone.upper()  # all to upper
            if tone[0] not in Letter:
                continue
            if len(tone)==4:
                display.showstatic(tone.replace(":",""))
            else:
                display.showstatic(tone)
            m = midi(tone)
            pwm.freq(m[0])  # set frequency
            pwm.duty(m[1])  # set duty cycle
            sleep_ms(m[1])
        display.clear()
    finally:
        pwm.deinit()
Example #2
0
    def connect(self, timeout=10000):
        self.wifi.active(True)
        self.wifi.connect(self.wifi_ssid, self.wifi_password)

        # -- wait until connected
        tmo = timeout/100
        while not self.wifi.isconnected():
            utime.sleep_ms(100)
            tmo -= 1
            if tmo == 0:
                print(Feedback.ERR_TIMEOUT_WIFI)
                return False

        # -- start mqtt
        if self.mqtt.status()[0] == 0:
            self.mqtt.start()

        tmo = timeout / 100
        while not self.mqtt.status()[0] == 2:
            utime.sleep_ms(100)
            tmo -= 1
            if tmo == 0:
                print(Feedback.ERR_TIMEOUT_MQTT)
                return False

        return True
Example #3
0
    def stop(self):
        """
        Stops the LoRaWAN nano gateway.
        """

        self._log('Stopping...')

        # send the LoRa radio to sleep
        self.lora.callback(trigger=None, handler=None)
        self.lora.power_mode(LoRa.SLEEP)

        # stop the NTP sync
        self.rtc.ntp_sync(None)

        # cancel all the alarms
        self.stat_alarm.cancel()
        self.pull_alarm.cancel()

        # signal the UDP thread to stop
        self.udp_stop = True
        while self.udp_stop:
            utime.sleep_ms(50)

        # disable WLAN
        self.wlan.disconnect()
        self.wlan.deinit()
Example #4
0
    def __init__(self, i2c, addr=0x77):
        self.i2c = i2c
        self.addr = addr
        self.chip_id = self.i2c.readfrom_mem(self.addr, 0xD0, 2)

        # read calibration data from EEPROM
        self._AC1 = unp('>h', self.i2c.readfrom_mem(self.addr, 0xAA, 2))[0]
        self._AC2 = unp('>h', self.i2c.readfrom_mem(self.addr, 0xAC, 2))[0]
        self._AC3 = unp('>h', self.i2c.readfrom_mem(self.addr, 0xAE, 2))[0]
        self._AC4 = unp('>H', self.i2c.readfrom_mem(self.addr, 0xB0, 2))[0]
        self._AC5 = unp('>H', self.i2c.readfrom_mem(self.addr, 0xB2, 2))[0]
        self._AC6 = unp('>H', self.i2c.readfrom_mem(self.addr, 0xB4, 2))[0]
        self._B1 = unp('>h', self.i2c.readfrom_mem(self.addr, 0xB6, 2))[0]
        self._B2 = unp('>h', self.i2c.readfrom_mem(self.addr, 0xB8, 2))[0]
        self._MB = unp('>h', self.i2c.readfrom_mem(self.addr, 0xBA, 2))[0]
        self._MC = unp('>h', self.i2c.readfrom_mem(self.addr, 0xBC, 2))[0]
        self._MD = unp('>h', self.i2c.readfrom_mem(self.addr, 0xBE, 2))[0]

        # settings to be adjusted by user
        self.oversample_setting = 3
        self.baseline = 101325.0

        # output raw
        self.UT_raw = None
        self.B5_raw = None
        self.MSB_raw = None
        self.LSB_raw = None
        self.XLSB_raw = None
        self.gauge = self.makegauge()  # Generator instance
        for _ in range(128):
            next(self.gauge)
            utime.sleep_ms(1)
Example #5
0
    def disconnect(self, timeout=5000):
        self.mqtt.stop()

        tmo = timeout / 100
        while not self.mqtt.status()[0] == 0:
            utime.sleep_ms(100)
            tmo -= 1
            if tmo == 0:
                print(Feedback.ERR_TIMEOUT_MQTT)
                return False

        if self.wifi.isconnected():
            self.wifi.disconnect()

        tmo = timeout / 100
        while self.wifi.isconnected():
            utime.sleep_ms(100)
            tmo -= 1
            if tmo == 0:
                print(Feedback.ERR_TIMEOUT_WIFI)
                return False

        self.wifi.active(False)

        return True
Example #6
0
    def angle(self, to_angle, speed=None, *servo_ids):
        if len(servo_ids) == 0:
            servo_ids = ServoJewel.ALL

        if speed is None:
            for s in servo_ids:
                self.servos[s].angle(to_angle)

        else:
            longest_range = 0
            ranges = {}
            for s in servo_ids:
                from_angle = self.servos[s].angle()
                if from_angle < to_angle:
                    ranges[s] = list(range(int(from_angle), to_angle + 5, 5))
                else:
                    ranges[s] = list(range(int(from_angle), to_angle - 5, -5))

                if longest_range < len(ranges[s]):
                    longest_range = len(ranges[s])

            for i in range(0, longest_range):
                for s in servo_ids:
                    if i >= len(ranges[s]):
                        continue

                    self.servos[s].angle(ranges[s][i])

                utime.sleep_ms(speed)
Example #7
0
 def calibrate(self,count=256,delay=200):
  self._offset=(0,0,0)
  self._scale=(1,1,1)
  reading=self.magnetic
  minx=maxx=reading[0]
  miny=maxy=reading[1]
  minz=maxz=reading[2]
  while count:
   utime.sleep_ms(delay)
   reading=self.magnetic
   minx=min(minx,reading[0])
   maxx=max(maxx,reading[0])
   miny=min(miny,reading[1])
   maxy=max(maxy,reading[1])
   minz=min(minz,reading[2])
   maxz=max(maxz,reading[2])
   count-=1
  offset_x=(maxx+minx)/2
  offset_y=(maxy+miny)/2
  offset_z=(maxz+minz)/2
  self._offset=(offset_x,offset_y,offset_z)
  avg_delta_x=(maxx-minx)/2
  avg_delta_y=(maxy-miny)/2
  avg_delta_z=(maxz-minz)/2
  avg_delta=(avg_delta_x+avg_delta_y+avg_delta_z)/3
  scale_x=avg_delta/avg_delta_x
  scale_y=avg_delta/avg_delta_y
  scale_z=avg_delta/avg_delta_z
  self._scale=(scale_x,scale_y,scale_z)
  return self._offset,self._scale
Example #8
0
 def show(self,data,delay=200,time=400):
  self.fill(0)
  if type(data)==str:
   DISPLAY_WIDTH=16
   DISPLAY_HEIGHT=8
   matrix=Display(i2c)
   def matrix_pixel(x,y):
    matrix._pixel(x,y,1)
   with BitmapFont(DISPLAY_WIDTH,DISPLAY_HEIGHT,matrix_pixel)as bf:
    for msg in data:
     matrix.clear()
     pos=DISPLAY_WIDTH
     message_width=bf.width(msg)
     bf.text(msg,5,0)
     matrix._show()
     if len(data)>1:
      utime.sleep_ms(delay)
  elif type(data)==int:
   pass
  elif type(data)==type(Image.HEART):
   l=data.str.split(':')
   for i in range(8):
    for j in range(16):
     if l[i][j]=='1':
      self._pixel(j,i,1)
     else:
      self._pixel(j,i,0)
   self._show()
Example #9
0
def play():
    #
    # pack of cards
    # select N from pack of cards
    for i in range(0, len(Master_Pack)):
        Pack.append(Master_Pack[i])
    deal(Number_of_cards_to_deal)
    #print("Remaining: ", Pack)
    #print("Selected: ", SelectedCards)
    N = len(SelectedCards)
    M = 0
    Score = 0
    print("")	
    print("Welcome to MicroPython Play your Cards Right")
    print("============================================")	
    while M < (N-1):
        #print("Turn: ", M)
        if turn(M):
            Score = Score + 1
        #print("Score: ", Score)
        M += 1		
        utime.sleep_ms(2000)
        # move to next card...
    print("Score: ", Score, "out of ", N-1)
    # Tidy Up
    for i in range(0, N):
        del SelectedCards[0]
    for i in range(0,len(Pack)):
        del Pack[0]	
    utime.sleep_ms(1000)
    red.off()
    grn.off()
    yel.on()
    print("Bye")
Example #10
0
 def show(self, data, delay=200, time=400):
     self.fill(0)
     if type(data)==str:
         DISPLAY_WIDTH  = 16      # Display width in pixels.
         DISPLAY_HEIGHT = 8       # Display height in pixels.
         # Initialize LED matrix.
         matrix = Display(i2c)
         #matrix.clear()
         # Initialize font renderer using a helper function to flip the Y axis
         # when rendering so the origin is in the upper left.
         def matrix_pixel(x, y):
             matrix._pixel(x, y, 1)
         with BitmapFont(DISPLAY_WIDTH, DISPLAY_HEIGHT, matrix_pixel) as bf:
             # Global state:
             for msg in data:
                 matrix.clear()
                 pos = DISPLAY_WIDTH                 # X position of the message start.
                 message_width = bf.width(msg)   # Message width in pixels.
                 bf.text(msg, 5, 0) #change X position
                 matrix._show()
                 if len(data)>1:
                     utime.sleep_ms(delay)    
     elif type(data)==int:
         pass
     elif type(data)==type(Image.HEART):
         # print("Image")
         l = data.str.split(':')
         for i in range(8):
             for j in range(16):
                 if l[i][j] == '1':
                     self._pixel(j, i, 1)
                 else:
                     self._pixel(j, i, 0)
                 #print(l[i][j])
         self._show()
Example #11
0
def slave():
    nrf = NRF24L01(SPI(2), Pin('Y5'), Pin('Y4'), payload_size=8)

    nrf.open_tx_pipe(pipes[1])
    nrf.open_rx_pipe(1, pipes[0])
    nrf.start_listening()

    print('NRF24L01 slave mode, waiting for packets... (ctrl-C to stop)')

    while True:
        machine.idle()
        if nrf.any():
            while nrf.any():
                buf = nrf.recv()
                millis, led_state = struct.unpack('ii', buf)
                print('received:', millis, led_state)
                for led in leds:
                    if led_state & 1:
                        led.on()
                    else:
                        led.off()
                    led_state >>= 1
                utime.sleep_ms(15)

            nrf.stop_listening()
            try:
                nrf.send(struct.pack('i', millis))
            except OSError:
                pass
            print('sent response')
            nrf.start_listening()
Example #12
0
def blinkIt():
	pin2 = machine.Pin(2, machine.Pin.OUT)
	for loopCount in range(10):
		pin2.value(1)
		utime.sleep_ms(500)
		pin2.value(0)
		utime.sleep_ms(500)
		print("hello")
Example #13
0
def master():
    csn = Pin(cfg['csn'], mode=Pin.OUT, value=1)
    ce = Pin(cfg['ce'], mode=Pin.OUT, value=0)
    if cfg['spi'] == -1:
        spi = SPI(-1, sck=Pin(cfg['sck']), mosi=Pin(cfg['mosi']), miso=Pin(cfg['miso']))
        nrf = NRF24L01(spi, csn, ce, payload_size=8)
    else:
        nrf = NRF24L01(SPI(cfg['spi']), csn, ce, payload_size=8)

    nrf.open_tx_pipe(pipes[0])
    nrf.open_rx_pipe(1, pipes[1])
    nrf.start_listening()

    num_needed = 16
    num_successes = 0
    num_failures = 0
    led_state = 0

    print('NRF24L01 master mode, sending %d packets...' % num_needed)

    while num_successes < num_needed and num_failures < num_needed:
        # stop listening and send packet
        nrf.stop_listening()
        millis = utime.ticks_ms()
        led_state = max(1, (led_state << 1) & 0x0f)
        print('sending:', millis, led_state)
        try:
            nrf.send(struct.pack('ii', millis, led_state))
        except OSError:
            pass

        # start listening again
        nrf.start_listening()

        # wait for response, with 250ms timeout
        start_time = utime.ticks_ms()
        timeout = False
        while not nrf.any() and not timeout:
            if utime.ticks_diff(utime.ticks_ms(), start_time) > 250:
                timeout = True

        if timeout:
            print('failed, response timed out')
            num_failures += 1

        else:
            # recv packet
            got_millis, = struct.unpack('i', nrf.recv())

            # print response and round-trip delay
            print('got response:', got_millis, '(delay', utime.ticks_diff(utime.ticks_ms(), got_millis), 'ms)')
            num_successes += 1

        # delay then loop
        utime.sleep_ms(250)

    print('master finished sending; successes=%d, failures=%d' % (num_successes, num_failures))
Example #14
0
 def run(self):
     while True:
         iteration_start = utime.ticks_ms()
         self.perform_tasks()
         time_spent_on_tasks = utime.ticks_diff(utime.ticks_ms(), iteration_start)
         if time_spent_on_tasks < self.sleep_ms:
             utime.sleep_ms(utime.ticks_diff(self.sleep_ms, time_spent_on_tasks))
         else:
             logger.warning('Skipping sleep - spent {}ms on tasks'.format(time_spent_on_tasks))
Example #15
0
def pwm_cycle(led, duty, cycles):
    duty_off = 20 - duty
    for i in range(cycles):
        if duty:
            led.on()
            utime.sleep_ms(duty)
        if duty_off:
            led.off()
            utime.sleep_ms(duty_off)
Example #16
0
    def blink(self, *eye_ids):
        if len(eye_ids) == 0:
            eye_ids = [0, 1]

        for m in Eyes.BLINK_MASK:
            for i in eye_ids:
                self.matrices.mask[i] = m

            utime.sleep_ms(50)
Example #17
0
 def iflush(self):
     t = 5000
     while t:
         self.i2c.readfrom_into(self.i2c_addr, self.buf16)
         if self.buf16[0] == 0:
             return
         t -= 1
         sleep_ms(1)
     raise OSError(uerrno.ETIMEDOUT)
Example #18
0
    def say_hello_right(self):
        self.lean_to_right(ServoJewel.SPEED_SLOW)

        for i in range(0, 3):
            self.servos.step_angle(120, ServoJewel.SPEED_SLOW, self.left_ankle)
            utime.sleep_ms(50)
            self.servos.step_angle(60, ServoJewel.SPEED_SLOW, self.left_ankle)
            utime.sleep_ms(50)

        self.undo_lean_to_right(ServoJewel.SPEED_SLOW)
Example #19
0
    def say_hello_left(self):
        self.lean_to_left(ServoJewel.SPEED_SLOW)

        for i in range(0, 3):
            self.servos.angle(MAX, ServoJewel.SPEED_SLOW, self.right_ankle)
            utime.sleep_ms(50)
            self.servos.angle(MIN, ServoJewel.SPEED_SLOW, self.right_ankle)
            utime.sleep_ms(50)

        self.undo_lean_to_left(ServoJewel.SPEED_SLOW)
Example #20
0
 def _waitfor(self, n, buf):
     t = 5000
     while t:
         self.i2c.readfrom_into(self.i2c_addr, self.buf1)
         if self.buf1[0] >= n:
             self.i2c.readfrom_into(self.i2c_addr, buf)
             return
         t -= 1
         sleep_ms(1)
     raise OSError(uerrno.ETIMEDOUT)
Example #21
0
def pitch(freq,pin=27,tim=1000):
 from machine import Pin,PWM
 from utime import sleep_ms
 try:
  pwm=PWM(Pin(pin))
  pwm.freq(freq)
  pwm.duty(tim)
  sleep_ms(tim)
 finally:
  pwm.deinit()
Example #22
0
    def start(self):
        """
        Starts the LoRaWAN nano gateway.
        """

        self._log('Starting LoRaWAN nano gateway with id: {}', self.id)

        # setup WiFi as a station and connect
        self.wlan = WLAN(mode=WLAN.STA)
        self._connect_to_wifi()

        # get a time sync
        self._log('Syncing time with {} ...', self.ntp_server)
        self.rtc.ntp_sync(self.ntp_server, update_period=self.ntp_period)
        while not self.rtc.synced():
            utime.sleep_ms(50)
        self._log("RTC NTP sync complete")

        # get the server IP and create an UDP socket
        self.server_ip = usocket.getaddrinfo(self.server, self.port)[0][-1]
        self._log('Opening UDP socket to {} ({}) port {}...', self.server, self.server_ip[0], self.server_ip[1])
        self.sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM, usocket.IPPROTO_UDP)
        self.sock.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
        self.sock.setblocking(False)

        # push the first time immediatelly
        self._push_data(self._make_stat_packet())

        # create the alarms
        self.stat_alarm = Timer.Alarm(handler=lambda t: self._push_data(self._make_stat_packet()), s=60, periodic=True)
        self.pull_alarm = Timer.Alarm(handler=lambda u: self._pull_data(), s=25, periodic=True)

        # start the UDP receive thread
        self.udp_stop = False
        _thread.start_new_thread(self._udp_thread, ())

        # initialize the LoRa radio in LORA mode
        self._log('Setting up the LoRa radio at {:.1f} Mhz using {}', self._freq_to_float(self.frequency), self.datarate)
        self.lora = LoRa(
            mode=LoRa.LORA,
            frequency=self.frequency,
            bandwidth=self.bw,
            sf=self.sf,
            preamble=8,
            coding_rate=LoRa.CODING_4_5,
            tx_iq=True
        )

        # create a raw LoRa socket
        self.lora_sock = usocket.socket(usocket.AF_LORA, usocket.SOCK_RAW)
        self.lora_sock.setblocking(False)
        self.lora_tx_done = False

        self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=self._lora_cb)
        self._log('LoRaWAN nano gateway online')
Example #23
0
 def pitch(self,pin=27,freq=440,tim=0):
  from machine import Pin,PWM
  from utime import sleep_ms
  pwm=PWM(Pin(pin))
  if freq>0:
   pwm.freq(int(freq))
  else:
   pwm.duty(0)
  if tim>0:
   sleep_ms(tim)
   pwm.deinit()
Example #24
0
 def get_pixel(self, x, y):
     self._fcmd2b('<BBBB', 0x61, x, y)
     t = 1000
     while t:
         self.i2c.readfrom_into(self.i2c_addr, self.buf1)
         if self.buf1[0] >= 2:
             self.i2c.readfrom_into(self.i2c_addr, self.buf[3])
             return self.buf[3][1] + self.buf[3][2] << 8
         t -= 1
         sleep_ms(1)
     raise OSError(uerrno.ETIMEDOUT)
Example #25
0
    def hal_write_command(self, cmd):
        """Writes a command to the LCD.

        Data is latched on the falling edge of E.
        """
        self.rs_pin.value(0)
        self.hal_write_8bits(cmd)
        if cmd <= 3:
            # The home and clear commands require a worst
            # case delay of 4.1 msec
            sleep_ms(5)
Example #26
0
 def recv(self, blocking=False):
     while blocking:
         sleep_ms(200)
         r = self.conn.recv(1024)
         if r is not None:
             return r
     try:
         sleep_ms(35)
         return self.conn.recv(1024)
     except:
         pass
Example #27
0
    def shake_right(self):
        self.lean_to_right(ServoJewel.SPEED_SLOW)

        for i in range(0, 3):
            self.servos.step_angle(120, ServoJewel.SPEED_FAST, self.left_hip)
            utime.sleep_ms(50)
            self.servos.step_angle(60, ServoJewel.SPEED_FAST, self.left_hip)
            utime.sleep_ms(50)

        self.servos.step_angle(90, ServoJewel.SPEED_FAST, self.left_hip)
        self.undo_lean_to_right(ServoJewel.SPEED_SLOW)
Example #28
0
 def _send(self, cmd):
     i = self.i2c.writeto(self.i2c_addr, cmd)
     if i == len(cmd):
         return
     cmd = memoryview(cmd)
     n = len(cmd)
     while True:
         i += self.i2c.writeto(self.i2c_addr, cmd[i:])
         if i == n:
             return
         sleep_ms(10)
Example #29
0
    def shake_left(self):
        self.lean_to_left(ServoJewel.SPEED_SLOW)

        for i in range(0, 3):
            self.servos.angle(MAX, ServoJewel.SPEED_FAST, self.right_hip)
            utime.sleep_ms(50)
            self.servos.angle(MIN, ServoJewel.SPEED_FAST, self.right_hip)
            utime.sleep_ms(50)

        self.servos.angle(CENTER, ServoJewel.SPEED_FAST, self.right_hip)
        self.undo_lean_to_left(ServoJewel.SPEED_SLOW)
Example #30
0
 def get_line(self, x, y, buf):
     l = len(buf) // 2
     self._fcmd2b('<BBBBB', 0x10, l, x, y)
     t = 1000
     while t:
         self.i2c.readfrom_into(self.i2c_addr, self.buf1)
         if self.buf1[0] >= l:
             self.i2c.readfrom_into(self.i2c_addr, buf)
             return
         t -= 1
         sleep_ms(1)
     raise OSError(uerrno.ETIMEDOUT)
Example #31
0
                i = 0

            # Process button event
            v = buttons.read(buttons.BOTTOM_LEFT | buttons.BOTTOM_RIGHT | buttons.TOP_RIGHT)
            if v == 0:
                button_pressed = False

            if not button_pressed and v & buttons.BOTTOM_LEFT != 0:
                button_pressed = True
                event_nb -= 1
                if event_nb < 0:
                    event_nb = 0
                offset = 0
                i = -7

            if not button_pressed and v & buttons.BOTTOM_RIGHT != 0:
                button_pressed = True
                event_nb += 1
                if event_nb >= len_events:
                    event_nb = len_events - 1
                offset = 0
                i = -7

            if not button_pressed and v & buttons.TOP_RIGHT != 0:
                button_pressed = True
                event_nb = compute_next_event_nb(events)
                offset = 0
                i = -7

            utime.sleep_ms(10)
Example #32
0

def run():
    playtestcounter = 0
    slotTriggered = None
    print("Monitoring Slots")
    while True:
        if slotTriggered is not None and playtestcounter >= playtestfrequency:
            playtestcounter = 0
            if not player.playing():
                slotTriggered = None
        playtestcounter += 1

        slotsUncovered = io.input_pins(inPins)
        if False in slotsUncovered:
            firstCovered = slotsUncovered.index(False)
            if firstCovered != slotTriggered:
                slotTriggered = firstCovered
                print("{} coin".format(firstCovered))
                if slotTriggered in player.tracks:
                    print("{} play".format(firstCovered))
                    player.playNext(slotTriggered)


# workaround for scanplayer which resets volume
sleep_ms(2000)  # TODO can this be removed? Belt and braces
player.awaitvolume()
player.volume(1.0)

run()
def ping(host, count=4, timeout=5000, interval=10, quiet=False, size=64):
    import utime
    import uselect
    import uctypes
    import usocket
    import ustruct
    import urandom

    # prepare packet
    assert size >= 16, "pkt size too small"
    pkt = b'Q' * size
    pkt_desc = {
        "type": uctypes.UINT8 | 0,
        "code": uctypes.UINT8 | 1,
        "checksum": uctypes.UINT16 | 2,
        "id": uctypes.UINT16 | 4,
        "seq": uctypes.INT16 | 6,
        "timestamp": uctypes.UINT64 | 8,
    }  # packet header descriptor
    h = uctypes.struct(uctypes.addressof(pkt), pkt_desc, uctypes.BIG_ENDIAN)
    h.type = 8  # ICMP_ECHO_REQUEST
    h.code = 0
    h.checksum = 0
    h.id = urandom.randint(0, 65535)
    h.seq = 1

    # init socket
    sock = usocket.socket(usocket.AF_INET, usocket.SOCK_RAW, 1)
    sock.setblocking(0)
    sock.settimeout(timeout / 1000)
    addr = usocket.getaddrinfo(host, 1)[0][-1][0]  # ip address
    sock.connect((addr, 1))
    not quiet and print("PING %s (%s): %u data bytes" % (host, addr, len(pkt)))

    seqs = list(range(1, count + 1))  # [1,2,...,count]
    c = 1
    t = 0
    n_trans = 0
    n_recv = 0
    finish = False
    while t < timeout:
        if t == interval and c <= count:
            # send packet
            h.checksum = 0
            h.seq = c
            h.timestamp = utime.ticks_us()
            h.checksum = checksum(pkt)
            if sock.send(pkt) == size:
                n_trans += 1
                t = 0  # reset timeout
            else:
                seqs.remove(c)
            c += 1

        # recv packet
        while 1:
            socks, _, _ = uselect.select([sock], [], [], 0)
            if socks:
                resp = socks[0].recv(4096)
                resp_mv = memoryview(resp)
                h2 = uctypes.struct(uctypes.addressof(resp_mv[20:]), pkt_desc,
                                    uctypes.BIG_ENDIAN)
                # TODO: validate checksum (optional)
                seq = h2.seq
                if h2.type == 0 and h2.id == h.id and (
                        seq in seqs):  # 0: ICMP_ECHO_REPLY
                    t_elasped = (utime.ticks_us() - h2.timestamp) / 1000
                    ttl = ustruct.unpack('!B', resp_mv[8:9])[0]  # time-to-live
                    n_recv += 1
                    not quiet and print(
                        "%u bytes from %s: icmp_seq=%u, ttl=%u, time=%f ms" %
                        (len(resp), addr, seq, ttl, t_elasped))
                    seqs.remove(seq)
                    if len(seqs) == 0:
                        finish = True
                        break
            else:
                break

        if finish:
            break

        utime.sleep_ms(1)
        t += 1

    # close
    sock.close()
    ret = (n_trans, n_recv)
    not quiet and print("%u packets transmitted, %u packets received" %
                        (n_trans, n_recv))
    return (n_trans, n_recv)
Example #34
0
import machine
import utime

servo = machine.PWM(machine.Pin(15))
servo.freq(50)


def interval_mapping(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min


def servo_write(pin, angle):
    pulse_width = interval_mapping(angle, 0, 180, 0.5, 2.5)
    duty = int(interval_mapping(pulse_width, 0, 20, 0, 65535))
    pin.duty_u16(duty)


while True:
    for angle in range(180):
        servo_write(servo, angle)
        utime.sleep_ms(20)
    for angle in range(180, -1, -1):
        servo_write(servo, angle)
        utime.sleep_ms(20)
thub = SmartHub()
thub.connect()

steer_trim = PBMotor("D")
thumb_trigger = PBMotor("C")
force_sensor = port.B.device
light_sensor = port.A.device
light_sensor.mode((2, 0))  # Ambient, Return Pct (0-100)
# roll0=motion.yaw_pitch_roll()[2]

while thub.is_connected() and not (button.center.is_pressed()):
    trim = steer_trim.angle() * 4

    # check rotation of the steering wheel with gyro roll
    steer_angle = motion.yaw_pitch_roll()[2] * 1.0

    # Check flappy paddles
    # Returns about 0 if both are pressed or released
    # Returns a positive number if the force sensor is pressed
    speed = force_sensor.get()[0] * 12 - (light_sensor.get()[0] - 40) * 2

    thub.dc(1, speed - steer_angle)
    sleep_ms(10)
    thub.dc(2, -speed - steer_angle)
    sleep_ms(10)

thub.dc(1, 0)
thub.dc(2, 0)
thub.disconnect()

raise SystemExit
        codes = ir.read()  # read IR code
        if len(codes) > 0 and codes[0] in keys:
            code = codes[0]
            print(code, keys[code])
            if code != '0':
                prev_key = keys[code]
            key = prev_key
            if key == 'UP':
                value = rgb[color]
                rgb[color] = min(value + 8, 255)
            elif key == 'DOWN':
                value = rgb[color]
                rgb[color] = max(value - 8, 0)
            elif key == 'HOME':
                rgb = 3 * [0]
                color = 0
            elif key in ['0', '1', '2']:
                color = int(key)
            elif key == 'POWER':
                break
            np[0] = tuple(rgb)
            np.write()
        time.sleep_ms(100)
except KeyboardInterrupt:
    pass
finally:
    ir.deinit()
    np[0] = (0, 0, 0)
    np.write()
    print('Done')
Example #37
0
import machine
import utime
# Creado por Daniel Alvarez ([email protected]) para curso de Python de EOI (eoi.es)

led = machine.Pin(2, machine.Pin.OUT)
# inicializamos otro pin, esta vez el 0 que es donde esta conectado el boton, y en modo entrada (IN)
boton = machine.Pin(
    0, machine.Pin.IN
)  # cambiar IN por PULL_UP para activar resistencia de pull-up

while True:  # bucle infinito
    # NOTA tal y como esta conectado el boton, pondra la linea a 0v si se pulsa y 3,3v si se libera
    estado_boton = boton.value()  # devuelve 0 si esta a 0v, o 1 si esta a 3,3v
    led.value(
        estado_boton
    )  # hacemos que el led se encienda o apague funcion del estado del boton
    # recordamos nuevamente que por la conexion del boton a la placa, trabajamos con logica negativa (al reves de lo "logico")
    if estado_boton:
        print("- boton liberado")
    else:
        print("X boton pulsado")
    utime.sleep_ms(100)  # hacemos una pausa para poder ver los prints
Example #38
0
 def reset(self):
     self.i2c_buffer[0] = RESET
     self.i2c_write(self.i2c_buffer)
     utime.sleep_ms(50)
'''
@Author: Baron
@Date: 2020-06-17
@LastEditTime: 2020-06-17 17:06:08
@Description: example for module utime
@FilePath: example_utime_sleep_file.py
'''
import utime
import log

# 设置日志输出级别
log.basicConfig(level=log.INFO)
time_log = log.getLogger("Sleep")

for i in [0, 1, 2, 3, 4, 5]:
    utime.sleep(1)  # 休眠(单位 m)
    time_log.info(i)

for i in [0, 1, 2, 3, 4, 5]:
    utime.sleep_ms(1000)  # 休眠(单位 ms)
    time_log.info(i)
Example #40
0
 def open_slowly(self):
     '''缓慢释放夹子'''
     for angle in range(100, 150, 1):
         self.grab(angle=angle)
         utime.sleep_ms(20)
Example #41
0
from machine import Pin, I2C
import utime
# Creado por Daniel Alvarez ([email protected]) para curso de Python de EOI (eoi.es)

i2c = I2C(
    1, sda=Pin(26), scl=Pin(32),
    freq=400000)  # instanciamos y configuramos bus I2C en los pines sda y scl

dispositivos_conectado = i2c.scan(
)  # manda mensajes por el bus i2c a todas las direcciones para ver que dispositivos contestan
# devuelve un listado de dispositivos conectados
print(
    dispositivos_conectado
)  # NOTA las direcciones las muestra en decimal, normalmente usaremos hexadecimal para trabajar con el i2c

from apds9930 import APDS9930
sensor = APDS9930(
    i2c)  # creamos una instancia del sensor y le pasamos el manejador del i2c
# el manejador del i2c lo creamos aqui porque si tenemos varios sensores en el bus, le pasamos el mismo manejador a todos

sensor.activar_proximidad(
)  # este metodo modifica un registro interno del APDS9930 para activar el sensor de proximidad

print("Acerca la mano al sensor para activarlo")
while True:
    proximidad = sensor.get_proximidad()
    if proximidad is not 0:
        print("Activado! lectura {}".format(proximidad))
        utime.sleep_ms(100)  # para que no sature la consola con prints
Example #42
0
 def out(self, freq=0, tim=0):
     self.pwm.freq(freq)
     self.pwm.duty(tim)
     sleep_ms(tim)
Example #43
0
    def start(self):
        """
        Starts the LoRaWAN nano gateway.
        """

        self._log('Starting LoRaWAN nano gateway with id: {}', self.id)

        # setup WiFi as a station and connect
        self.wlan = WLAN(mode=WLAN.STA)
        self._connect_to_wifi()

        # get a time sync
        self._log('Syncing time with {} ...', self.ntp_server)
        self.rtc.ntp_sync(self.ntp_server, update_period=self.ntp_period)
        while not self.rtc.synced():
            utime.sleep_ms(50)
        self._log("RTC NTP sync complete")

        # get the server IP and create an UDP socket
        self.server_ip = usocket.getaddrinfo(self.server, self.port)[0][-1]
        self._log('Opening UDP socket to {} ({}) port {}...', self.server,
                  self.server_ip[0], self.server_ip[1])
        self.sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM,
                                   usocket.IPPROTO_UDP)
        self.sock.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
        self.sock.setblocking(False)

        # push the first time immediatelly
        self._push_data(self._make_stat_packet())

        # create the alarms
        self.stat_alarm = Timer.Alarm(
            handler=lambda t: self._push_data(self._make_stat_packet()),
            s=60,
            periodic=True)
        self.pull_alarm = Timer.Alarm(handler=lambda u: self._pull_data(),
                                      s=25,
                                      periodic=True)

        # start the UDP receive thread
        self.udp_stop = False
        _thread.start_new_thread(self._udp_thread, ())

        # initialize the LoRa radio in LORA mode
        self._log('Setting up the LoRa radio at {:.1f} Mhz using {}',
                  self._freq_to_float(self.frequency), self.datarate)
        self.lora = LoRa(mode=LoRa.LORA,
                         frequency=self.frequency,
                         bandwidth=self.bw,
                         sf=self.sf,
                         preamble=8,
                         coding_rate=LoRa.CODING_4_5,
                         tx_iq=True)

        # create a raw LoRa socket
        self.lora_sock = usocket.socket(usocket.AF_LORA, usocket.SOCK_RAW)
        self.lora_sock.setblocking(False)
        self.lora_tx_done = False

        self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT
                                    | LoRa.TX_PACKET_EVENT),
                           handler=self._lora_cb)
        self._log('LoRaWAN nano gateway online')
Example #44
0
import machine
import utime

pin0 = machine.Pin(0, machine.Pin.OUT)
pin2 = machine.Pin(2, machine.Pin.OUT)

while True:
    for i in range(0, 10):
        pin0.off()
        pin2.on()
        utime.sleep_ms(60)
        pin0.on()
        pin2.off()
        utime.sleep_ms(60)
    pin0.on()
    pin2.on()
    utime.sleep_ms(500)
Example #45
0
def default_wait():
    '''
    delay of 50 ms
    '''
    sleep_ms(50)
Example #46
0
print("---------------------------------------------------------------------")
print("|  Module HC-06 configuration                                       |")
print("|  enter AT              -- To test serial communication            |")
print("|  enter AT+NAME??????   -- To modify the module name               |")
print("|  enter AT+PIN????      -- To modify the module PIN code           |")
print("|  enter AT+BAUD4        -- To modify the module communication speed|")
print("|  Note: 1 for 1200,  2 for 2400,  3 for 4800,  4 for 9600          |")
print("|        5 for 19200, 6 for 38400, 7 for 57600, 8 for 115200        |")
print("---------------------------------------------------------------------")

while True:
    print("ENTER AT Commands: ")
    try:
        str = input()
        uart.write(str)
        utime.sleep_ms(100)
    except OSError:
        pass

    # wait for response
    start_time = utime.ticks_ms()
    timeout = False
    while not uart.any() and not timeout:
        if utime.ticks_diff(utime.ticks_ms(), start_time) > 500:
            timeout = True
    if timeout:
        print('Failed, response timed out')
    else:
        buf = uart.read()
        print("received:", buf)
    utime.sleep_ms(600)
Example #47
0
 def encender_led_aleatorio(self):
     aleatorio = random.getrandbits(12)
     aleatorio += 3000
     time.sleep_ms(aleatorio)
     self.led.value(0)
Example #48
0
 def initialize(self):
     utime.sleep_ms(3)
     self.softreset()
     # print(self.getdeviceid())
     if self.get_deviceid() is not 0x13:
         return 0
Example #49
0
 def _initialize(self) -> None:
     self.i2c.writeto(SHT31_DEVICE_ADDRESS,
                      bytearray([CMD_SOFT_RESET_ADDR,
                                 CMD_SOFT_RESET_VAL]))  # reset
     sleep_ms(2)  # 0.5 to 1 ms according to datasheet
Example #50
0
async def foo():
    while True:
        await asyncio.sleep(0)
        utime.sleep_ms(10)  # Emulate slow processing
Example #51
0
play = __music__.play


def old_pitch(self, freq, tim, pin=25):
    from machine import Pin, PWM
    from utime import sleep_ms

    try:
        pwm = PWM(Pin(pin))
        pwm.freq(freq)  # set frequency
        pwm.duty(tim)  # set duty cycle
        sleep_ms(tim)
    finally:
        pwm.deinit()


pitch = old_pitch

set_tempo = __music__.set_tempo
stop = __music__.stop

if __name__ == '__main__':
    unit_test()

    play(NYAN)
    sleep_ms(1000)

    pitch(range(880, 1760, 16), 30)
    sleep_ms(50)
Example #52
0
def unit_test():
    tmp = music()

    tmp.play(POWER_UP)
    sleep_ms(500)
    tmp.play(POWER_UP)
    sleep_ms(1000)
    tmp.play(POWER_DOWN)
    sleep_ms(500)
    tmp.play(POWER_DOWN)
    sleep_ms(1000)

    tmp.pitch(range(880, 1760, 16), 30)
    sleep_ms(50)
    tmp.pitch(range(1760, 880, -16), 30)
    sleep_ms(50)

    tmp.play(BIRTHDAY)
    sleep_ms(15000)
    tmp.play(NYAN)
    sleep_ms(10000)
    tmp.play(PRELUDE)
    sleep_ms(10000)
    tmp.play(PYTHON)
    sleep_ms(10000)

    tmp.__del__()
Example #53
0
 def wait(self, delay):
     # Default wait implementation, to be overriden in subclasses
     # with IO scheduling
     if __debug__ and DEBUG:
         log.debug("Sleeping for: %s", delay)
     time.sleep_ms(delay)
Example #54
0
##Author: Marcelo Soares Barroso
##Data: 01/07/2018
##Objetivo: fazer um acendimento sequencial cuja velocidade seja crescente iniciando em 2 segundos a espera e diminuindo até 0,5 segundos. Utilize quatros estágios, e reinicie após a ocorrência dos mesmos.

import utime
import machine

pin23 = machine.Pin(23, machine.Pin.OUT)
pin22 = machine.Pin(22, machine.Pin.OUT)
pin21 = machine.Pin(21, machine.Pin.OUT)
pin18 = machine.Pin(18, machine.Pin.OUT)
pin19 = machine.Pin(19, machine.Pin.OUT)

while True:
    pin23.value(1)
    utime.sleep_ms(2000)
    pin23.value(0)
    pin22.value(1)
    utime.sleep_ms(2000)
    pin22.value(0)
    pin21.value(1)
    utime.sleep_ms(2000)
    pin21.value(0)
    pin18.value(1)
    utime.sleep_ms(2000)
    pin18.value(0)
    pin19.value(1)
    utime.sleep_ms(2000)
    pin23.value(0)
    pin22.value(0)
    pin21.value(0)
Example #55
0
        # print("red: {:03d}, green: {:03d}, blue: {:03d}".format(self.red,
        #                                                        self.green,
        #                                                        self.blue))
        return (self.red, self.green, self.blue)


pin = Pin(NEO_PIXEL_PIN, Pin.OUT)
np = NeoPixel(pin, NO_OF_LEDS)
brightness = 0.1

wheel = ColorWheel()

wheel_pos = [None] * NO_OF_LEDS

print("Each led shows all colors of the color wheel")
print("The color wheel starting position of led i is i * 360° / no of leds")

for led in range(NO_OF_LEDS):
    wheel_pos[led] = int(360 / NO_OF_LEDS * led)
    # print("wheel pos for led {:d}: {:d}".format(led,wheel_pos[led]))

while True:
    for i in range(360):
        for led in range(NO_OF_LEDS):
            colors = wheel.colors((wheel_pos[led] + i) % 360)
            np[led] = (int(colors[0] * brightness),
                       int(colors[1] * brightness),
                       int(colors[2] * brightness))
            np.write()
        sleep_ms(2)
Example #56
0
 def lire_pulsation(self):
     ppm = i2c.read(0x50, 1, False)
     sleep_ms(self._delay)
     if (self._debug):
         print("[debug] Pulsation : ", ppm)
     return ord(ppm)
Example #57
0
from utime import sleep_ms, ticks_ms, ticks_add, ticks_diff, time
import ntptime
from umqtt.simple import MQTTClient
import ubinascii, machine
import urequests as requests
import wifiportal

np = NeoPixel(Pin(2), 24)
np.write()

for r in range(8):
    np[r] = (20, 0, 0)
    np[r + 8] = (0, 20, 0)
    np[r + 16] = (0, 0, 20)
    np.write()
    sleep_ms(50)

wifiportal.captive_portal("RfidLock")

try:
    ntptime.settime()
except:
    pass

for r in range(8):
    np[r] = (0, 0, 0)
    np[r + 8] = (0, 0, 0)
    np[r + 16] = (0, 0, 0)
    np.write()
    sleep_ms(50)
Example #58
0
def do_menu(g):
    global module_name, vol, max_vol

    # all dislplay, buttons, paddle, sound logics are in game8266.mpy module

    SKIP_NAMES = ("boot", "main", "menu", "gameogo")

    files = [item[0] for item in os.ilistdir(".") if item[1] == 0x8000]

    module_names = [
        filename.rsplit(".", 1)[0] for filename in files
        if (filename.endswith(".py") or filename.endswith(".mpy"))
        and not filename.startswith("_")
    ]
    module_names = [
        module_name for module_name in module_names
        if not module_name in SKIP_NAMES
    ]
    module_names.sort()
    tot_file = len(module_names)
    COLOR_FG = g.tft.GREEN
    COLOR_BG = g.tft.BLACK
    COLOR_HH = g.tft.RED
    g.tft.font(g.tft.FONT_Ubuntu)
    fontW, fontH = g.tft.fontSize()
    rowH = fontH + 2
    tot_rows = g.screenH // rowH - 1
    screen_pos = 0
    file_pos = 0
    updateMenu = True
    launched = False
    while not launched:
        gc.collect()
        g.getBtn()
        g.setVol()

        if updateMenu:
            updateMenu = False
            g.tft.clear(g.tft.BLACK)
            g.tft.set_bg(COLOR_BG)
            g.tft.text(0, 0, 'M:{}'.format(gc.mem_free()), g.tft.RED)
            g.display_vol()
            i = 0
            for j in range(file_pos, min(file_pos + tot_rows, tot_file)):
                if i == screen_pos:
                    g.display_msg(0, rowH * (i + 1),
                                  str(j) + " " + module_names[j], COLOR_FG,
                                  COLOR_HH)
                else:
                    g.display_msg(0, rowH * (i + 1),
                                  str(j) + " " + module_names[j], COLOR_FG,
                                  COLOR_BG)
                i += 1

        if g.justPressed(g.btnU):
            if screen_pos > 0:
                g.display_msg(
                    0, rowH * (screen_pos + 1),
                    str(file_pos + screen_pos) + " " +
                    module_names[file_pos + screen_pos], COLOR_FG, COLOR_BG)
                screen_pos -= 1
                g.display_msg(
                    0, rowH * (screen_pos + 1),
                    str(file_pos + screen_pos) + " " +
                    module_names[file_pos + screen_pos], COLOR_FG, COLOR_HH)

            else:
                if file_pos > 0:
                    file_pos = max(0, file_pos - tot_rows)
                    screen_pos = tot_rows - 1
                    updateMenu = True
            g.playTone('c4', tone_dur)

        if g.justPressed(g.btnD):
            if screen_pos < min(tot_file - file_pos - 1, tot_rows - 1):
                g.display_msg(
                    0, rowH * (screen_pos + 1),
                    str(file_pos + screen_pos) + " " +
                    module_names[file_pos + screen_pos], COLOR_FG, COLOR_BG)
                screen_pos = min(tot_file - 1, screen_pos + 1)
                g.display_msg(
                    0, rowH * (screen_pos + 1),
                    str(file_pos + screen_pos) + " " +
                    module_names[file_pos + screen_pos], COLOR_FG, COLOR_HH)
            else:
                if file_pos + tot_rows < tot_file:
                    file_pos = min(tot_file, file_pos + tot_rows)
                    screen_pos = 0
                    updateMenu = True
            g.playTone('e4', tone_dur)

        if g.justReleased(g.btnA):
            g.playTone('c5', tone_dur)
            g.tft.clear(g.tft.BLACK)
            g.center_msg(
                "launching {}".format(module_names[file_pos + screen_pos]),
                COLOR_FG, COLOR_BG)
            sleep_ms(1000)
            module_name = module_names[file_pos + screen_pos]
            return True

        if g.justReleased(g.btnL):
            g.playTone('d5', tone_dur)
            launched = True
            g.tft.clear(g.tft.BLACK)
            g.center_msg("Exited", COLOR_FG, COLOR_BG)
            return False
        sleep_ms(10)
Example #59
0
 def grab_slowly(self):
     '''缓慢夹取'''
     for angle in range(150, 100, -1):
         self.grab(angle=angle)
         utime.sleep_ms(20)
Example #60
0
# file: ir_receiver_demo-1.py
# https://medium.com/@rawat.s/micropython-programming-for-esp32-14-3474eeccdddd
from machine import Pin
import utime as time
from ir_receiver import IR_RECV
ir = IR_RECV(Pin(12), timeout=80)
try:
    while True:
        codes = ir.read()
        for code in codes:
            print("Code: '{}'".format(code))
        time.sleep_ms(300)
except KeyboardInterrupt:
    pass
finally:
    ir.deinit()
    print('Done')