Example #1
0
 def __writeSetup(self):
     self.p7 = pyb.Pin(7)
     self.p7.init(pyb.Pin.OUT_PP,pyb.Pin.PULL_NONE)
     pyb.delay(1)
     self.p8 = pyb.Pin(8)
     self.p8.init(pyb.Pin.IN,pyb.Pin.PULL_NONE)
     pyb.delay(1)
Example #2
0
    def test_8(self):
        self.__writeSetup()

        self.p7.low()
        pyb.delay(10)
        v = self.p8.value()
        self.assertEqual(v,0,"Write Low test")        
Example #3
0
    def init_uart(self, uart_bus, baud_rate, update_rate):
        self.uart = pyb.UART(uart_bus, baud_rate, read_buf_len=1000)

        pyb.delay(50)

        # get RMC and GGA sentences at 1 hz
        if update_rate == 1:
            self.send_command(PMTK_SET_NMEA_OUTPUT_RMCGGA)
            self.send_command(PMTK_SET_NMEA_UPDATE_1HZ)
            self.send_command(PMTK_API_SET_FIX_CTL_1HZ)
        elif update_rate == 5:
            # get RMC and GGA sentences at 5 hz
            self.send_command(PMTK_SET_NMEA_OUTPUT_RMCGGA)
            self.send_command(PMTK_SET_NMEA_UPDATE_5HZ)
            self.send_command(PMTK_API_SET_FIX_CTL_5HZ)
        elif update_rate == 10:
            if baud_rate == 9600:  # send less data if using slower baud rate
                self.send_command(PMTK_SET_NMEA_OUTPUT_RMCONLY)
            elif baud_rate == 57600:
                self.send_command(PMTK_SET_NMEA_OUTPUT_RMCGGA)
            else:
                raise ValueError("Invalid baud rate:", baud_rate)

            self.send_command(PMTK_SET_NMEA_UPDATE_10HZ)
            # fix can't update at 10 hz
            self.send_command(PMTK_API_SET_FIX_CTL_5HZ)
        else:
            raise ValueError("Invalid update rate:", update_rate)
Example #4
0
def test_main():
    """Test function for verifying basic functionality."""
    print("Running test_main")
    i2c = I2C(1, I2C.MASTER)
    lcd = I2cLcd(i2c, 0x27, 2, 16)
    lcd.putstr("It Works!\nSecond Line")
    delay(3000)
    lcd.clear()
    count = 0
    while True:
        lcd.move_to(0, 0)
        lcd.putstr("%7d" % (millis() // 1000))
        delay(1000)
        count += 1
        if count % 10 == 3:
            print("Turning backlight off")
            lcd.backlight_off()
        if count % 10 == 4:
            print("Turning backlight on")
            lcd.backlight_on()
        if count % 10 == 5:
            print("Turning display off")
            lcd.display_off()
        if count % 10 == 6:
            print("Turning display on")
            lcd.display_on()
        if count % 10 == 7:
            print("Turning display & backlight off")
            lcd.backlight_off()
            lcd.display_off()
        if count % 10 == 8:
            print("Turning display & backlight on")
            lcd.backlight_on()
            lcd.display_on()
Example #5
0
def cycleAll():
    vals = [0 for i in range(nbShiftRegs)]
    for i in range(nbShiftRegs):
        for j in range(8):
            vals[i] |= 1<<j
            testSPI(vals)
            delay(100)
Example #6
0
    def __init__(self, pinout, height=32, external_vcc=True, i2c_devid=DEVID):
        self.external_vcc = external_vcc
        self.height = 32 if height == 32 else 64
        self.pages = int(self.height / 8)
        self.columns = 128

        # Infer interface type from entries in pinout{}
        if "dc" in pinout:
            # SPI
            rate = 1 * 1024 * 1024
            self.spi = pyb.SPI(2, pyb.SPI.MASTER, baudrate=rate, polarity=1, phase=0)  # SCK: Y6: MOSI: Y8
            self.dc = pyb.Pin(pinout["dc"], pyb.Pin.OUT_PP, pyb.Pin.PULL_DOWN)
            self.cs = pyb.Pin(pinout["cs"], pyb.Pin.OUT_PP, pyb.Pin.PULL_DOWN)
            self.offset = 0
            self.cs.high()
            pyb.delay(100)
            self.cs.low()
        else:
            # Infer bus number from pin
            if pinout["sda"] == "X9":
                self.i2c = pyb.I2C(1)
            else:
                self.i2c = pyb.I2C(2)
            self.i2c.init(pyb.I2C.MASTER, baudrate=400000)  # 400kHz
            self.devid = i2c_devid
            # used to reserve an extra byte in the image buffer AND as a way to
            # infer the interface type
            self.offset = 1
            # I2C command buffer
            self.cbuffer = bytearray(2)
            self.cbuffer[0] = CTL_CMD
Example #7
0
 def mainLoop(self):
     while True:
         if polling:
             self.pollPollables()
         self.processQ()
         # put a sleep comand here to save energy
         pyb.delay(self.mainLoopDelay)
Example #8
0
def main_client(addr):
    nic = network.WIZNET5K(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4)
    nic.ifconfig((SENSOR_IP, SENSOR_MASK, SENSOR_GATEWAY, SENSOR_DNS))
    # print(nic.ifconfig())
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    count = 0
    try:
        s.connect(addr)
    except:
        pass
    data = {
        'serial_no':'1234567890',
        'ip':SENSOR_IP,
        'op':gOperator['OP_REGISTER'],
        'type':gSensorType['TEMPERATURE']
    }
    DHT22.init()
    while True:
        pyb.delay(100)
        hum, tem = measure()
        print('%d hum:%f, tem:%f' % (count,hum, tem))
        data['value'] = {'hum':hum, 'tem':tem}
        count += 1

        try:
            send(s, 'post', '/test_pymagic', data)
            print(s.recv(4096))
        except:
            pass
        pyb.delay(1000)
 def test_6(self):
     t0 = pyb.Timer(0)
     t0.init(freq=1000)
     t0.counter(0)
     pyb.delay(100)
     t0.deinit()
     self.assertGT(t0.counter(), 8, "timer counter")
Example #10
0
def run(cName='X7',dName='X8'):
    p = PS2a.PS2(cName,dName)

    mInit(p)

    #setup local loop variabls 
    lmStat = 'y'
    mStat =  'n'
    lmx = '1'
    mx = '0'
    lmy = '1'
    my = '0'

    outputTemplate = 'X=%d\tY=%d\t%s'
    
    while True:
        p.write(0XEB)  # poll
        print('Write POLL')
        p.read()       # ignore the ACK
        mstat = p.read()  # status byte
        mx    = p.read()  # delta-x byte
        my    = p.read()  # delta-y byte

        if mstat != lmstat or mx != lmx or my != lmy:
            print (outputTemplate%(mx,my,interpretStat(mstat)))
            lmstat = mstat
            lmx = mx
            lmy =my
        pyb.delay(20)
Example #11
0
    def _communicate(self, request, number_of_bytes_to_read):
        _checkInt(number_of_bytes_to_read)

        # Sleep to make sure 3.5 character times have passed
        minimum_silent_period   = _calculate_minimum_silent_period(self.serial.get_baudrate())
        pyb.delay(minimum_silent_period)

        # Write request
        self.serial.write(request)


        # Read response
        answer = bytearray()
        timeOutRead = 200
        while True:
            if self.serial.any():
                answer = self.serial.read(number_of_bytes_to_read)
                break
            else:
                pyb.delay(10)
                timeOutRead-=1
                if timeOutRead<=0:
                    break
        #_________                       

        if len(answer) == 0:
            raise Exception('No communication with the instrument (no answer)')

        return answer
Example #12
0
def lcd_fun():
    # Main program block
    lcd = HD44780()

    # Pins 0-5 as above
    lcd.PINS = ['Y1','Y2','Y3','Y4','Y5','Y6']

    # Initialise display
    lcd.init()

    # Use it
    lcd.set_line(0) # First line
    lcd.set_string("ABCDEFGHIJKLMNOP") # Send a string
    lcd.set_line(1) # Second line
    lcd.set_string("1234567890123456") # Again

    pyb.delay(3000) # 3 second delay

    # Send some more
    lcd.set_line(0)
    lcd.set_string("*micropython-lcd")
    lcd.set_line(1)
    lcd.set_string("github.com/wjdp")

    pyb.delay(3000)

    # Done
    lcd.clear()
 def brake( self ) :
   """ Brake the motor by sending power both directions. """
   self._forward.high()
   self._backward.high()
   self._speedControl.pulse_width_percent = 100
   delay(1000)
   self.speed = 0
Example #14
0
    def test_9(self):
        self.__writeSetup()

        self.p7.high()
        pyb.delay(10)
        v = self.p8.value()
        self.assertEqual(v,1,"Write High test")
Example #15
0
def wait_for_connection():
    print( "wifi.py: wait_for_connection()" )
    global _state
    while not nic().is_connected():
        nic().update()
        pyb.delay(100)
    _state = NICState.CONNECTED
 def hal_write_command(self, cmd):
     """Writes a command to the LCD."""
     self.i2c.mem_write(cmd, self.i2c_addr, self.LCD_DDRAM)
     if cmd <= 3:
         # The home and clear commands require a worst
         # case delay of 4.1 msec
         delay(5)
Example #17
0
def hdc1080_read(a=0):
    b1[0] = a
    i2c.writeto(64, b1)
    pyb.delay(dt)
    i2c.readfrom_into(64, b2)
    #return '%02x%02x' % (b[0], b[1])
    return (b2[0] << 8) | b2[1]
Example #18
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:
        pyb.wfi()
        if nrf.any():
            while nrf.any():
                buf = nrf.recv()
                millis, led_state = struct.unpack('ii', buf)
                print('received:', millis, led_state)
                for i in range(4):
                    if led_state & (1 << i):
                        pyb.LED(i + 1).on()
                    else:
                        pyb.LED(i + 1).off()
                pyb.delay(15)

            nrf.stop_listening()
            try:
                nrf.send(struct.pack('i', millis))
            except OSError:
                pass
            print('sent response')
            nrf.start_listening()
Example #19
0
def testrgb( display ) :
  print("bgr")
  display.rgb(False) #bgr
  pyb.delay(2000)
  print("rgb")
  display.rgb(True) #rgb
  pyb.delay(1000)
Example #20
0
    def __init__(self, spi_port, pin_rst, pin_dc):
        self.spi = spi_port
        if type(self.spi) == pyb.SPI:
            self.spi.init(pyb.SPI.MASTER, baudrate=600000, polarity=0)
        elif type(self.spi) == SoftSPI:
            self.spi.polarity = 0            
        self.rst_value = pyb.Pin(pin_rst, pyb.Pin.OUT_PP).value
        self.dc_value = pyb.Pin(pin_dc, pyb.Pin.OUT_PP).value

        # Reset
        self.dc_value(0)
        self.rst_value(0)
        pyb.delay(1)
        self.rst_value(1)
        pyb.delay(1)

        # Init
        self.dc_value(0)
        self.spi.send(0x21) # LCD Extended Commands.
        self.spi.send(0x9f) # Set LCD Vop
        self.spi.send(0x06) # Set Temp coefficent.
        #self.spi.send(0x15) # BIAS
        self.spi.send(0x20) # LCD Standard Commands
        self.spi.send(0x0c) # LCD in normal mode D=1 E=0 (&h0d- invert)
        self.spi.send(0x1b)
        self.dc_value(1)
Example #21
0
def testline( display ) :
  print('testing line')
  displaysize = display.size()
  start = (int(displaysize[0] / 2), int(displaysize[1] / 2))
  px = 0
  py = 0

  def draw(x, y) :
    display.line(start, (x, y), randcolor())

  for x in range(displaysize[0]) :
    draw(px, py)
    px += 1

  for y in range(displaysize[1]) :
    draw(px, py)
    py += 1

  for x in range(displaysize[0]) :
    draw(px, py)
    px -= 1

  for y in range(displaysize[1]) :
    draw(px, py)
    py -= 1
  pyb.delay(2000)
Example #22
0
def run(sensitivity = 100):
    """
    does the init steps and then loops on poll calls
    """
    if not sensitivity or sensitivity >100:
        print('Sensitivity is a percent and must be on [100,1]')
        return
    
    s = round(minPollDelay * 100/ sensitivity)
    
    # init the is1 module
    is1.i()
    
    # reset the trackball
    is1.r()
          # set trackball to remote, i.e. polling mode
    is1.m()
    while True:
          # recover x,y offsets
        (x,y) = is1.p()
        # if there has been some movement, process it
        if x !=0 or y!=0 :
            process(x,y)
            lx=x
            ly=y
        # give some time to do other stuff!
        pyb.delay(s)
Example #23
0
def loop():
    global mstat,lmstat,mx,lmx,my,lmy,maxX,maxY
    #get a reading from the mouse */
    mouseWrite(0xeb) #  /* give me data! */
    mouseRead()    #  /* ignore ack */
    mstat = mouseRead()
    mx = mouseRead()
    my = mouseRead()

    if((mstat != lmstat) or
       (mx !=lmx) or
       (my != lmy)):
      #/* send the data back up */
      #//Serial.print(mstat, BIN);
        print('X=',str(mx),'\tY=',str(my) + interpretStatByte(mstat))
        lmstat = mstat
        lmx = mx
        lmy = my
        #maxX = max(mx,maxX);
        #maxY = max(my,maxY);
        """
        Serial.print("maxX: ");
        Serial.print(maxX,DEC);
        Serial.print("\tmaxY: ");
        Serial.println(maxY,DEC);
        """
        pyb.delay(20)
def test():
    mpu9150 = MPU9150("X")
    testfunc(mpu9150)
    print()
    pyb.delay(250)
    print("Repeating")
    testfunc(mpu9150)
def  uart_hash():
	#  initialize UART(6) to output TX on Pin Y1
	uart = UART(6)
	while True:
		uart.init(9600, bits=8, parity = 0, stop = 2)
		uart.writechar(ord('#'))		# letter '#'
		pyb.delay(5)					# delay by 5ms
Example #26
0
def flash():		# routine to flash blue LED when beat detected

	b_LED.on()

	pyb.delay(30)

	b_LED.off()
Example #27
0
def calibrate():
    with open("calibration.txt", "r") as f:
        data = f.read()
        while True:
            print(clear_screen, end="")
            print(data, end="")
            pyb.delay(200)
Example #28
0
def clear_tastes(tastes = ['Y1', 'Y2', 'Y3', 'Y4'], duration = 10000):
	for i in tastes:
		pyb.Pin(i, pyb.Pin.OUT_PP).high()
	pyb.delay(duration)
	for i in tastes:
		pyb.Pin(i, pyb.Pin.OUT_PP).low()
	print('The purge is complete.  This has been the most sucessful purge yet.')
Example #29
0
def FadingLEDPWM(cnt=10, step = 1.07, ledNdx1 = 1, ledNdx2 = 2):
	led = pyb.LED(ledNdx1)
	led2 = pyb.LED(ledNdx2)
	bri = 1.0
	dir = 1
	while cnt:
		if dir == 1:
			bri *= step
			if bri > 270:
				bri = 255
				dir = -1
				print("Fading out")
		else:
			bri /= step
			if bri < 1:
				dir = 1
				bri = 1
				print("Fading in")
				cnt -= 1
		intbri = int(bri)
		if intbri > 255:
			intbri = 255
		led.intensity(intbri)
		led2.intensity(intbri)
		pyb.delay(25)
	print("exiting")
def	ultrasound():
	
	Trigger = Pin('X3', Pin.OUT_PP)
	Echo = Pin('X4',Pin.IN)
	
	# Create a microseconds counter.
	micros = pyb.Timer(2, prescaler=83, period=0x3fffffff)
	micros.counter(0)
	start = 0
	end = 0
	
	# Send a 20usec pulse every 10ms
	while True:
		Trigger.high()
		pyb.udelay(20)
		Trigger.low()
		
		# Wait until pulse starts
		while Echo.value() == 0:   # do nothing
			start = micros.counter()	# mark time at rising edge
		
		# Wait until pulse goes low
		while Echo.value() == 1:   # do nothing
			end = micros.counter()		# mark time at falling edge
		
		# Duration echo pulse = end - start
		# Divide this by 2 to take account of round-trip
		# Speed of sound in air is 340 m/s or 29 us/cm
		# Distance in cm = (pulse_width)*0.5/29
		distance = int(((end - start) / 2) / 29)
		print('Distance: ', distance, ' cm')
		pyb.delay(500)
Example #31
0
def flash():
    b_LED.on()
    pyb.delay(20)
    b_LED.off()
Example #32
0
    def dealWithUnicastREQ(self, payload):

        # Note the time of receiving this packet
        reqTime = utime.ticks_ms()

        # Parse the source address
        srcNode = struct.unpack('B', payload[3:4])[0]

        # If this is the first REQ or a repeated REQ (retransmissions)
        reqIndex = struct.unpack('B', payload[4:5])[0]

        # Check if I need to go back to always-on state after this
        sleepFlag = struct.unpack('B', payload[5:6])[0]

        # Decode the addresses of nodes expected to respond
        destAddr = list()
        for n in range(7, len(payload)):
            addr = struct.unpack('B', payload[n:n + 1])[0]
            destAddr.append(int(addr))

        # Print message for debugging
        print("Unicast REQ received from Node " + str(srcNode))

        # If this is a blank REQ (e.g. go-to-sleep instruction)
        if not destAddr:

            # Transmit a blank broadcast REQ to my child nodes three times
            numREQCopies = 3
            interval = 2000  # 2 second intervals between REQ copies
            for n in range(numREQCopies):

                # Feed the watchdog
                if self.wdt:
                    self.wdt.feed()

                # Transmit blank broadcast REQ
                ttnf = max(
                    0, self.timeTillNextFrame -
                    utime.ticks_diff(utime.ticks_ms(), self.ttnfTimestamp))
                print("Sending Blank Broadcast REQ...")
                gwf.sendBroadcastREQ(self.nm, "S", n + 1, ttnf,
                                     (sleepFlag == 1), [])
                # Wait for a set interval before transmitting it again
                pyb.delay(interval)

        # If this is not a blank REQ gather the data from my child nodes
        else:

            # Try gathering the data from all child nodes
            packetBuffer = list()
            nodesToRespond = destAddr.copy()
            numRetries = 3
            for n in range(1, numRetries + 1):

                # Feed the watchdog
                if self.wdt:
                    self.wdt.feed()

                # Transmit a broadcast REQ packet
                ttnf = max(
                    0, self.timeTillNextFrame -
                    utime.ticks_diff(utime.ticks_ms(), self.ttnfTimestamp))
                print("Sending Broadcast REQ...")
                gwf.sendBroadcastREQ(self.nm, payload[6:7].decode(), n, ttnf,
                                     (sleepFlag == 1), nodesToRespond)

                # Go into a loop listening for payload packets from child nodes
                sfStartTime = utime.ticks_ms()
                timeout = self.subframeLength + 2 * self.guardInt
                while utime.ticks_diff(utime.ticks_ms(),
                                       utime.ticks_add(sfStartTime,
                                                       timeout)) < 0:

                    # Feed the watchdog
                    if self.wdt:
                        self.wdt.feed()

                    # Check if a packet has been received
                    self.nm.poll_receiver()
                    self.nm.process_incoming_buffer()
                    if self.nm.has_received_packet():
                        # Decode the packet
                        packet = self.nm.get_received_packet()
                        payload = bytes(packet.packet_payload)
                        # If the source address is one of the child nodes
                        srcAddr = struct.unpack('B', payload[3:4])[0]
                        if (payload[0:3] == b'UND') and (srcAddr
                                                         in self.childNodes):
                            # Store the packet in the forwarding buffer and take out the child node out of the list
                            print("  Data packet received from N" +
                                  "%03d" % srcAddr)
                            packetBuffer.append(packet)
                            nodesToRespond.remove(srcAddr)

                    # Add a delay before checking the serial port again
                    pyb.delay(25)

                # If there are no more child nodes to gather data from, do not transmit a REQ again
                if not nodesToRespond:
                    break

            # Transmit a START DATA TRANSFER handshake packet to the gateway and wait for an ACK
            numTries = 5
            timeout = 5.0
            gwReady = False
            for n in range(numTries):

                # Feed the watchdog
                if self.wdt:
                    self.wdt.feed()

                # Transmit a short handshake packet "UNSDT", if ACK is received, proceed with data transfer
                print("Contacting GW to initiate data transfer...")
                delay = self.nm.send_unicast_message_with_ack(
                    srcNode, b'UNSDT', timeout)
                if delay > 0:
                    print("  GW is ready to receive")
                    gwReady = True
                    break

            # Forward all payload packets in the buffer to the node that requested it
            # Wait for a Repeated REQ in case retransmissions are required
            frameIsOver = False
            while gwReady and (not frameIsOver):

                # Forward the packets
                for fwPacket in packetBuffer:

                    # Feed the watchdog
                    if self.wdt:
                        self.wdt.feed()

                    # Send the packet
                    payload = bytes(fwPacket.packet_payload)
                    srcAddr = struct.unpack('B', payload[3:4])[0]

                    # Transmit the payload packet if this node was specified in the REQ
                    if (srcAddr in destAddr):
                        print("Forwarding data packet from Node " +
                              str(srcAddr) + " to Node " + str(srcNode) +
                              "...")
                        self.nm.send_unicast_message(srcNode, payload)
                        pyb.delay(
                            gwf.dataPktDur + self.guardInt
                        )  # delay while we are transmitting the packet

                # If there are any child nodes who did not respond with a data packet
                for unrNode in nodesToRespond:
                    if unrNode in destAddr:

                        # Feed the watchdog
                        if self.wdt:
                            self.wdt.feed()

                        # Send blank packets to the Gateway
                        payload = b'UND' + struct.pack('B',
                                                       unrNode) + b'no_packet'
                        print("Sending blank data packet from Node " +
                              str(unrNode) + " to Node " + str(srcNode) +
                              "...")
                        self.nm.send_unicast_message(srcNode, payload)
                        pyb.delay(
                            gwf.dataPktDur + self.guardInt
                        )  # delay while we are transmitting the packet

                # Wait for a repeated REQ asking for retransmissions (10 sec timeout)
                txEndTime = utime.ticks_ms()
                timeout = 10000
                anotherREQReceived = False
                while utime.ticks_diff(utime.ticks_ms(),
                                       utime.ticks_add(txEndTime,
                                                       timeout)) < 0:

                    # Feed the watchdog
                    if self.wdt:
                        self.wdt.feed()

                    # Check if a packet has been received
                    self.nm.poll_receiver()
                    self.nm.process_incoming_buffer()
                    if self.nm.has_received_packet():
                        # Read the incoming packet and see if it is a REQ
                        packet = self.nm.get_received_packet()
                        payload = bytes(packet.packet_payload)
                        srcId = packet.source_address
                        pktType = packet.packet_type
                        # If it is a REQ, resend some of the packets again
                        if (pktType == 'U') and (len(payload) > 4) and (
                                payload[0:3] == b'UNR'):

                            # Check if I need to go back to always-on state after this
                            anotherREQReceived = True
                            sleepFlag = struct.unpack('B', payload[5:6])[0]

                            # Decode the addresses of nodes expected to respond
                            destAddr = list()
                            for n in range(7, len(payload)):
                                addr = struct.unpack('B', payload[n:n + 1])[0]
                                destAddr.append(int(addr))
                                # Transmit the missing packets again (by staying in this loop)
                        # Otherwise, pass it up to the main packet handling function
                        else:
                            (canGoToSleep, _,
                             pktIgnored) = self.handle_packet(packet)[0]
                            if not pktIgnored:
                                sleepFlag = 1 if (
                                    canGoToSleep
                                ) else 0  # Convert the sleep flag (due to recursion here!)

                # Check if the frame is over
                frameIsOver = not anotherREQReceived

        # Return the sleep flag
        return (sleepFlag == 1)
Example #33
0
count_ = 0


def ChangeLEDState(num_):
    global leds
    len_ = len(leds)
    for i in range(0, len_):
        if i != num_:
            leds[i].off()
        else:
            leds[i].on()


while True:
    u2.init(2400, bits=8, parity=None, stop=1)
    pyb.delay(80)
    Quality = 'DATA NULL'
    if (u2.any() > 0):
        u2.deinit()
        _dataRead = u2.readall()
        #R代表截取数据的起始位
        R = _dataRead.find(b'\xaa')
        #R>-1代表存在起始位,长度大于起始位位置+2
        if R > -1 and len(_dataRead) > (R + 2):
            P = _dataRead[R + 1]
            L = _dataRead[R + 2]
            #把串口收到的十六进制数据转换成十进制
            SHI = P * 256 + L
            SHUCHU = SHI / G * A
        if (SHUCHU < 35):
            Quality = 'Excellente'
Example #34
0
def touch_pos():
    #local switch
    #screen_sw = pyb.Switch()
    #initiate values
    #lcd.set_text_color(lcd.rgb(255, 0, 0), lcd.rgb(0, 0, 0))
    #
    lcd.erase()
    #t,x,y = lcd.get_touch()
    exit = 0

    #draw touch areas
    fg = lcd.rgb(255, 128, 128)
    bg = lcd.rgb(0, 0, 0)
    lcd.set_pen(fg, bg)
    #rect(x,y,w,h)
    lcd.rect(2, 2, 50, 80)
    lcd.set_pos(5, 5)
    lcd.write('S 1')
    pyb.delay(500)

    lcd.set_pen(fg, lcd.rgb(128, 128, 128))
    lcd.rect(2, 82, 50, 78)
    lcd.set_pos(5, 85)
    lcd.write('S 2')
    pyb.delay(500)

    lcd.set_pen(fg, lcd.rgb(96, 96, 96))
    lcd.rect(53, 2, 50, 80)
    lcd.set_pos(56, 5)
    lcd.write('S 3')
    pyb.delay(500)

    lcd.set_pen(fg, lcd.rgb(64, 64, 64))
    lcd.rect(53, 82, 50, 78)
    lcd.set_pos(56, 85)
    lcd.write('S 4')

    lcd.set_pen(fg, lcd.rgb(128, 0, 0))
    lcd.rect(105, 2, 15, 160)
    lcd.set_pos(106, 5)
    lcd.write('exit')

    pyb.delay(2000)

    while exit == 0:

        #lcd.erase()
        t, x, y = lcd.get_touch()
        lcd.set_pos(15, 150)
        lcd.write(str(t))
        lcd.set_pos(45, 150)
        lcd.write('   ')
        lcd.set_pos(45, 150)
        lcd.write(str(x))
        lcd.set_pos(75, 150)
        lcd.write('   ')
        lcd.set_pos(75, 150)
        lcd.write(str(y))

        lcd.set_pos(105, 150)
        if (x > 105):
            exit = 1
        if (x < 53 and y < 82):
            lcd.write('S1')
        if (x < 53 and y > 82):
            lcd.write('S2')
        if (x > 53 and y < 82):
            lcd.write('S3')
        if (x > 53 and y > 82):
            lcd.write('S4')

        #sleep(1) # pyboard also doesn't recognize input
        pyb.delay(1000)  #alternative
    lcd.erase()
    lcd.set_pos(20, 80)
    lcd.write('EXIT TOUCH TEST')

    pyb.delay(2000)
import pyb

from libraries.mpu6050 import MPU6050
from libraries.hmc5883l import HMC5883L

from libraries.fusion import Fusion

imu = MPU6050(1, False)
compass = HMC5883L(1, declination=(-9, 16))

fuse = Fusion()

sw = pyb.Switch()
fuse.calibrate(compass.axes, sw, lambda: pyb.delay(100))
print(fuse.magbias)

count = 0
while True:
    fuse.update(imu.get_acc(), imu.get_gyro(), compass.axes())
    # if count % 50 == 0:
    print("Heading, Pitch, Roll: {:7.3f} {:7.3f} {:7.3f}".format(
        fuse.heading, fuse.pitch, fuse.roll))
    pyb.delay(20)
    count += 1
Example #36
0
# Make sure it is ready
while True:
    check_ready = True
    if DO_SCAN:
        slaves = i2c.scan()
        print("I2C device addresses: " + ", ".join([str(slave) for slave in slaves]))
        if not FDC_ADDR in slaves:
            check_ready = False
    if check_ready:
        if (i2c.is_ready(FDC_ADDR)):
            print("Ready!")
            break
        else:
            print("FDC is not ready.")
    pyb.delay(1000)

# Setup
print("Starting setup:")
for cmd in setup_sequence:
    print("\t" + cmd[0])
    i2c.send(bytearray(cmd[1]), addr=FDC_ADDR)
print("Setup done")

# Do checks
print("Starting checks")
regscan(do_print=True)

if __name__ == "__main__":
    print("Starting streaming")
    while True:
Example #37
0
fuse = Fusion()

# Choose test to run
Calibrate = True
Timing = False


def getmag():  # Return (x, y, z) tuple (blocking read)
    return imu.mag.xyz


if Calibrate:
    print("Calibrating. Press switch when done.")
    sw = pyb.Switch()
    fuse.calibrate(getmag, sw, lambda: pyb.delay(100))
    print(fuse.magbias)

if Timing:
    mag = imu.mag.xyz  # Don't include blocking read in time
    accel = imu.accel.xyz  # or i2c
    gyro = imu.gyro.xyz
    start = pyb.micros()
    fuse.update(accel, gyro, mag)  # 1.65mS on Pyboard
    t = pyb.elapsed_micros(start)
    print("Update time (uS):", t)

count = 0
while True:
    fuse.update(imu.accel.xyz, imu.gyro.xyz,
                imu.mag.xyz)  # Note blocking mag read
Example #38
0
# main.py -- put your code here!
import pyb

switch = pyb.Switch()
accel = pyb.Accel()

while True:
	pyb.hid((switch(), accel.x(), -accel.y(), 0))
	pyb.delay(20)
Example #39
0
     # break
 if new_data:
     while True:
         my_gps.update(chr(uart.readchar()))
     if my_gps.latitude[0] != 0:
         xbee.write('\nChecking GPS and altitude to see if landed...')
         initial_lat = convert_latitude(my_gps.latitude)
         initial_long = convert_longitude(my_gps.longitude)
         initial_point = (initial_lat, initial_long)
         xbee.write('\nCurrent point: {}'.format(initial_point))
         dist_from_launch = calculate_distance(launch_point, initial_point)
         xbee.write('\nDistance from launch: {}'.format(dist_from_launch))
         # acceptable distance is currently set for simple testing
         if dist_from_launch < acceptable_dist_from_launch:
             # pyb.stop()
             pyb.delay(100)
         elif dist_from_launch > acceptable_dist_from_launch:
             altitude_1 = my_gps.altitude
             pyb.delay(10000) # change to 10000 for real launch
             altitude_2 = my_gps.altitude
             altitude_change = abs(altitude_1 - altitude_2)
             xbee.write('\nAltitude change: {}'.format(altitude_change))
             if altitude_change > acceptatble_altitude_change:
                 # pyb.stop()
                 pyb.delay(100)
             elif altitude_change < acceptatble_altitude_change and pyb.elapsed_millis(start) >= altitude_concurrent_timer: # acceptable time yet to be determined
                 break
         elif pyb.elapsed_millis(start) >= backup_timer:
             break
         new_data = False
         past_point2 = None
def conway_go(num_frames):
    for i in range(num_frames):
        conway_step()  # do 1 iteration
        lcd.show()  # update the LCD
        pyb.delay(50)
Example #41
0
tim.prescaler(300)
print(tim.prescaler())
tim.period(400)
print(tim.period())

tim = Timer(4, freq=1)
tim.init(freq=2000)


def f(t):
    print(1)
    t.callback(None)


tim.callback(f)
pyb.delay(10)


# f3 closes over f2.y
def f2(x):
    y = x

    def f3(t):
        print(2, y)
        t.callback(None)

    return f3


tim.callback(f2(3))
pyb.delay(10)
Example #42
0
import pyb
from BioloidController import BioloidController
from Support import RangeFinder


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


blue = pyb.LED(4)

ranger = RangeFinder('C3')
controller = BioloidController()
controller.rampServoTo(13, 306)
values = []
pyb.delay(250)
blue.on()
totalStart = pyb.millis()
for position in range(30600, 71700, 1705):
    start = pyb.millis()
    end = start + 40
    i_pos = int(position / 100)
    controller.setPosition(13, i_pos)
    values.append(ranger.getDistance())
    pyb.delay(max(0, end - pyb.millis()))

blue.off()

print("Total time: ", (pyb.millis() - totalStart))
# controller.rampServoTo(13, 511)
print(values)
Example #43
0
#初始化ADC
Soil = pyb.ADC('B1')

#显示标题
d.printStr('01Studio Soil Test', 10, 10, BLACK, size=4)
while True:

    value = Soil.read()  #获取ADC数值

    #LCD显示
    d.printStr('Vol:' + str('%.2f' % (value / 4095 * 3.3)) + " V",
               10,
               100,
               BLACK,
               size=4)
    d.printStr('Value:' + str(value) + "   ", 10, 200, BLACK, size=4)
    d.printStr("(4095)", 300, 200, BLACK, size=4)

    #判断土壤湿度,分3档位显示
    if 0 < value <= 1247:
        d.printStr('Dry   ', 10, 300, BLACK, size=4)

    if 1247 < value <= 2238:
        d.printStr('Normal', 10, 300, BLACK, size=4)

    if 2238 < value <= 4095:
        d.printStr('Wet   ', 10, 300, BLACK, size=4)

    pyb.delay(1000)  #延时1秒
Example #44
0
    pass

print(can.recv(0))

try:
    can.send('abcde', 2, timeout=0)
    can.send('abcde', 3, timeout=0)
    can.send('abcde', 4, timeout=0)
    can.send('abcde', 5, timeout=0)
except OSError as e:
    if str(e) == '16':
        print('passed')
    else:
        print('failed')

pyb.delay(500)
while can.any(0):
    print(can.recv(0))

# Testing rtr messages
bus1 = CAN(1, CAN.LOOPBACK)
while bus1.any(0):
    bus1.recv(0)
bus1.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4))
bus1.setfilter(1, CAN.LIST16, 0, (5, 6, 7, 8), rtr=(True, True, True, True))
bus1.setfilter(2, CAN.MASK16, 0, (64, 64, 32, 32), rtr=(False, True))

bus1.send('', 1, rtr=True)
print(bus1.any(0))
bus1.send('', 5, rtr=True)
print(bus1.recv(0))
Example #45
0
 def reset(self):
     self.i2c.writeto_mem(self.addr, RFD77402_COMMAND, b'x40')  # 1<<6
     pyb.delay(10)
Example #46
0
	for i in tastes:
		pyb.Pin(i, pyb.Pin.OUT_PP).high()
	pyb.delay(duration)
	for i in tastes:
		pyb.Pin(i, pyb.Pin.OUT_PP).low()
	print('The purge is complete.  This has been the most sucessful purge yet.')

# This is for manual shaping of behavior.

def shape(maxtrials = 100, outport = 'Y2', opentime = 12)
	i = 0
	inport = 'X6'
	while i < maxtrials:
		if pyb.Pin(inport, pyb.Pin.IN).value() == 0:
			pyb.Pin(outport, pyb.Pin.OUT_PP).high()
			pyb.delay(opentime)
			pyb.Pin(outport, pyb.Pin.OUT_PP).low()
			pyb.delay(500)
			i += 1
			print(str(i)+' rewards given.')

# Water passive habituation
				
def passive_water(outport = 'Y2', opentime = 12, trials = 50, iti = 15000):
	i = 1	# trial counter
	while i <= trials:
		pyb.Pin(outport, pyb.Pin.OUT_PP).high()
		pyb.delay(opentime)
		pyb.Pin(outport, pyb.Pin.OUT_PP).low()
		i = i+1
		pyb.delay(iti)
cpufreq.set_frequency(216)

sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QQVGA)
sensor.set_windowing((120, 120))
sensor.set_contrast(3)
sensor.set_auto_exposure(True)
sensor.skip_frames(time=2000)

uart = UART(3, 115200)  #Cambiar a la velocidad que se inicializa en arduino

clock = time.clock()

LED(1).on()
pyb.delay(300)
LED(2).on()
pyb.delay(300)
LED(3).on()

min_degreeV = 0
max_degreeV = 5

minDegreeH = 88
maxDegreeH = 94

min_degreeS = 95
max_degreeS = 112

##################################################################3
Example #48
0
def one_round():
    grid_size = 8
    body_colour = ugfx.RED
    back_colour = 0
    food_colour = ugfx.YELLOW
    wall_colour = ugfx.BLUE
    score = 0
    edge_x = math.floor(ugfx.width() / grid_size) - 2
    edge_y = math.floor(ugfx.height() / grid_size) - 2

    def disp_square(x, y, colour):
        ugfx.area((x + 1) * grid_size, (y + 1) * grid_size, grid_size,
                  grid_size, colour)

    def disp_body_straight(x, y, rotation, colour):
        if (rotation == 0):
            ugfx.area((x + 1) * grid_size + 1, (y + 1) * grid_size + 1,
                      grid_size - 2, grid_size, colour)
        elif (rotation == 90):
            ugfx.area((x + 1) * grid_size + 1, (y + 1) * grid_size + 1,
                      grid_size, grid_size - 2, colour)
        elif (rotation == 180):
            ugfx.area((x + 1) * grid_size + 1, (y + 1) * grid_size - 1,
                      grid_size - 2, grid_size, colour)
        else:
            ugfx.area((x + 1) * grid_size - 1, (y + 1) * grid_size + 1,
                      grid_size, grid_size - 2, colour)

    def disp_eaten_food(x, y, colour):
        ugfx.area((x + 1) * grid_size, (y + 1) * grid_size, grid_size,
                  grid_size, colour)

    def randn_square():
        return [pyb.rng() % edge_x, pyb.rng() % edge_y]

    body_x = [12, 13, 14, 15, 16]
    body_y = [2, 2, 2, 2, 2]

    ugfx.area(0, 0, ugfx.width(), ugfx.height(), 0)

    ugfx.area(0, 0, grid_size * (edge_x + 1), grid_size, wall_colour)
    ugfx.area(0, 0, grid_size, grid_size * (edge_y + 1), wall_colour)
    ugfx.area(grid_size * (edge_x + 1), 0, grid_size, grid_size * (edge_y + 1),
              wall_colour)
    ugfx.area(0, grid_size * (edge_y + 1), grid_size * (edge_x + 2), grid_size,
              wall_colour)

    keepgoing = 1

    food = [20, 20]
    disp_square(food[0], food[1], food_colour)

    dir_x = 1
    dir_y = 0
    orient = 270

    #for i in range(0,len(body_x)):
    #   disp_body_straight(body_x[i],body_y[i],orient,body_colour)

    while keepgoing:
        if buttons.is_pressed("JOY_RIGHT"):
            dir_x = 1
            dir_y = 0
            orient = 270
        elif buttons.is_pressed("JOY_LEFT"):
            dir_x = -1
            dir_y = 0
            orient = 90
        elif buttons.is_pressed("JOY_DOWN"):
            dir_y = 1
            dir_x = 0
            orient = 180
        elif buttons.is_pressed("JOY_UP"):
            dir_y = -1
            dir_x = 0
            orient = 0

        body_x.append(body_x[-1] + dir_x)
        body_y.append(body_y[-1] + dir_y)

        for i in range(0, len(body_x) - 1):
            if (body_x[i] == body_x[-1]) and (body_y[i] == body_y[-1]):
                keepgoing = 0

        if not ((body_x[-1] == food[0]) and (body_y[-1] == food[1])):
            x_del = body_x.pop(0)
            y_del = body_y.pop(0)
            disp_eaten_food(x_del, y_del, back_colour)
        else:
            disp_eaten_food(food[0], food[1], body_colour)
            food = randn_square()
            disp_square(food[0], food[1], food_colour)
            score = score + 1

        disp_body_straight(body_x[-1], body_y[-1], orient, body_colour)

        if ((body_x[-1] >= edge_x) or (body_x[-1] < 0)
                or (body_y[-1] >= edge_y) or (body_y[-1] < 0)):
            break

        pyb.delay(100)
    return score
pinD = pyb.Pin('P2', pyb.Pin.OUT_PP, pyb.Pin.PULL_NONE)

# Create a timer object running at 1KHz which which will power the
# PWM output on our OpenMV Cam. Just needs to be created once.
tim = pyb.Timer(4, freq=1000)

# These PWM channels will set the PWM percentage on the H-Bridge
# driver pair above. If you'd like to change the driver power
pinABPower = tim.channel(1,
                         pyb.Timer.PWM,
                         pin=pyb.Pin("P7"),
                         pulse_width_percent=100)
pinCDPower = tim.channel(2,
                         pyb.Timer.PWM,
                         pin=pyb.Pin("P8"),
                         pulse_width_percent=100)

while (True):

    pyb.delay(1000)
    pinA.value(0)
    pinB.value(1)
    pinC.value(0)
    pinD.value(1)

    pyb.delay(1000)
    pinA.value(1)
    pinB.value(0)
    pinC.value(1)
    pinD.value(0)
Example #50
0
 def reset(self):
     self.__reset_pin.low()
     pyb.delay(2)
     self.__reset_pin.high()
     pyb.delay(6)
Example #51
0
    def tft_init(self,
                 controller="SSD1963",
                 lcd_type="LB04301",
                 orientation=LANDSCAPE,
                 v_flip=False,
                 h_flip=False,
                 power_control=True):
        #
        # For convenience, define X1..X1 and Y9..Y12 as output port using thy python functions.
        # X1..X8 will be redefind on the fly as Input by accessing the MODER control registers
        # when needed. Y9 is treate seperately, since it is used for Reset, which is done at python level
        # since it need long delays anyhow, 5 and 15 ms vs. 10 µs.
        #
        # Set TFT general defaults
        self.controller = controller
        self.lcd_type = lcd_type
        self.orientation = orientation
        self.v_flip = v_flip  # flip vertical
        self.h_flip = h_flip  # flip horizontal
        self.c_flip = 0  # flip blue/red
        self.rc_flip = 0  # flip row/column

        self.tft_io = TFT_IO()

        self.setColor((255, 255, 255))  # set FG color to white as can be.
        self.setBGColor((0, 0, 0))  # set BG to black
        self.bg_buf = bytearray()
        #
        self.pin_led = None  # deferred init Flag
        self.power_control = power_control
        if self.power_control:
            # special treat for Power Pin
            self.pin_power = pyb.Pin("Y4", pyb.Pin.OUT_PP)
            self.power(True)  ## switch Power on
#
        pyb.delay(10)
        # this may have to be moved to the controller specific section
        if orientation == PORTRAIT:
            self.setXY = self.tft_io.setXY_P
            self.drawPixel = self.tft_io.drawPixel_P
        else:
            self.setXY = self.tft_io.setXY_L
            self.drawPixel = self.tft_io.drawPixel_L
        self.swapbytes = self.tft_io.swapbytes
        self.swapcolors = self.tft_io.swapcolors
        #  ----------
        for pin_name in [
                "X1", "X2", "X3", "X4", "X5", "X6", "X7", "X8", "Y10", "Y11",
                "Y12"
        ]:
            pin = pyb.Pin(pin_name, pyb.Pin.OUT_PP)  # set as output
            pin.value(1)  ## set high as default
# special treat for Reset
        self.pin_reset = pyb.Pin("Y9", pyb.Pin.OUT_PP)
        # Reset the device
        self.pin_reset.value(1)  ## do a hard reset
        pyb.delay(10)
        self.pin_reset.value(0)  ## Low
        pyb.delay(20)
        self.pin_reset.value(1)  ## set high again
        pyb.delay(20)
        #
        # Now initialiize the LCD
        # This is for the SSD1963 controller and two specific LCDs. More may follow.
        # Data taken from the SSD1963 data sheet, SSD1963 Application Note and the LCD Data sheets
        #
        if controller == "SSD1963":  # 1st approach for 480 x 272
            self.tft_io.tft_cmd_data(
                0xe2, bytearray(b'\x1d\x02\x54'),
                3)  # PLL multiplier, set PLL clock to 100M
            # N=0x2D for 6.5MHz, 0x1D for 10MHz crystal
            # PLLClock = Crystal * (Mult + 1) / (Div + 1)
            # The intermediate value Crystal * (Mult + 1) must be between 250MHz and 750 MHz
            self.tft_io.tft_cmd_data(0xe0, bytearray(b'\x01'), 1)  # PLL Enable
            pyb.delay(10)
            self.tft_io.tft_cmd_data(0xe0, bytearray(b'\x03'), 1)
            pyb.delay(10)
            self.tft_io.tft_cmd(0x01)  # software reset
            pyb.delay(10)
            #
            # Settings for the LCD
            #
            # The LCDC_FPR depends on PLL clock and the reccomended LCD Dot clock DCLK
            #
            # LCDC_FPR = (DCLK * 1048576 / PLLClock) - 1
            #
            # The other settings are less obvious, since the definitions of the SSD1963 data sheet and the
            # LCD data sheets differ. So what' common, even if the names may differ:
            # HDP  Horizontal Panel width (also called HDISP, Thd). The value store in the register is HDP - 1
            # VDP  Vertical Panel Width (also called VDISP, Tvd). The value stored in the register is VDP - 1
            # HT   Total Horizontal Period, also called HP, th... The exact value does not matter
            # VT   Total Vertical Period, alco called VT, tv, ..  The exact value does not matter
            # HPW  Width of the Horizontal sync pulse, also called HS, thpw.
            # VPW  Width of the Vertical sync pulse, also called VS, tvpw
            # Front Porch (HFP and VFP) Time between the end of display data and the sync pulse
            # Back Porch (HBP  and VBP Time between the start of the sync pulse and the start of display data.
            #      HT = FP + HDP + BP  and VT = VFP + VDP + VBP (sometimes plus sync pulse width)
            # Unfortunately, the controller does not use these front/back porch times, instead it uses an starting time
            # in the front porch area and defines (see also figures in chapter 13.3 of the SSD1963 data sheet)
            # HPS  Time from that horiz. starting point to the start of the horzontal display area
            # LPS  Time from that horiz. starting point to the horizontal sync pulse
            # VPS  Time from the vert. starting point to the first line
            # FPS  Time from the vert. starting point to the vertical sync pulse
            #
            # So the following relations must be held:
            #
            # HT >  HDP + HPS
            # HPS >= HPW + LPS
            # HPS = Back Porch - LPS, or HPS = Horizontal back Porch
            # VT > VDP + VPS
            # VPS >= VPW + FPS
            # VPS = Back Porch - FPS, or VPS = Vertical back Porch
            #
            # LPS or FPS may have a value of zero, since the length of the front porch is detemined by the
            # other figures
            #
            # The best is to start with the recomendations of the lCD data sheet for Back porch, grab a
            # sync pulse with and the determine the other, such that they meet the relations. Typically, these
            # values allow for some ambuigity.
            #
            if lcd_type == "LB04301":  # Size 480x272, 4.3", 24 Bit, 4.3"
                #
                # Value            Min    Typical   Max
                # DotClock        5 MHZ    9 MHz    12 MHz
                # HT (Hor. Total   490     531      612
                # HDP (Hor. Disp)          480
                # HBP (back porch)  8      43
                # HFP (Fr. porch)   2       8
                # HPW (Hor. sync)   1
                # VT (Vert. Total) 275     288      335
                # VDP (Vert. Disp)         272
                # VBP (back porch)  2       12
                # VFP (fr. porch)   1       4
                # VPW (vert. sync)  1       10
                #
                # This table in combination with the relation above leads to the settings:
                # HPS = 43, HPW = 8, LPS = 0, HT = 531
                # VPS = 14, VPW = 10, FPS = 0, VT = 288
                #
                self.disp_x_size = 479
                self.disp_y_size = 271
                self.tft_io.tft_cmd_data_AS(0xe6, bytearray(b'\x01\x70\xa3'),
                                            3)  # PLL setting for PCLK
                # (9MHz * 1048576 / 100MHz) - 1 = 94371 = 0x170a3
                self.tft_io.tft_cmd_data_AS(
                    0xb0,
                    bytearray(  # # LCD SPECIFICATION
                        [
                            0x20,  # 24 Color bits, HSync/VSync low, No Dithering
                            0x00,  # TFT mode
                            self.disp_x_size >> 8,
                            self.disp_x_size & 0xff,  # physical Width of TFT
                            self.disp_y_size >> 8,
                            self.disp_y_size & 0xff,  # physical Height of TFT
                            0x00
                        ]),
                    7)  # Last byte only required for a serial TFT
                self.tft_io.tft_cmd_data_AS(
                    0xb4, bytearray(b'\x02\x13\x00\x2b\x08\x00\x00\x00'), 8)
                # HSYNC,  Set HT 531  HPS 43   HPW=Sync pulse 8 LPS 0
                self.tft_io.tft_cmd_data_AS(
                    0xb6, bytearray(b'\x01\x20\x00\x0e\x0a\x00\x00'), 7)
                # VSYNC,  Set VT 288  VPS 14 VPW 10 FPS 0
                self.tft_io.tft_cmd_data_AS(
                    0x36,
                    bytearray([(orientation & 1) << 5 | (h_flip & 1) << 1 |
                               (v_flip) & 1]), 1)
                # rotation/ flip, etc., t.b.d.
            elif lcd_type == "AT070TN92":  # Size 800x480, 7", 18 Bit, lower color bits ignored
                #
                # Value            Min     Typical   Max
                # DotClock       26.4 MHz 33.3 MHz  46.8 MHz
                # HT (Hor. Total   862     1056     1200
                # HDP (Hor. Disp)          800
                # HBP (back porch)  46      46       46
                # HFP (Fr. porch)   16     210      254
                # HPW (Hor. sync)   1                40
                # VT (Vert. Total) 510     525      650
                # VDP (Vert. Disp)         480
                # VBP (back porch)  23      23       23
                # VFP (fr. porch)   7       22      147
                # VPW (vert. sync)  1                20
                #
                # This table in combination with the relation above leads to the settings:
                # HPS = 46, HPW = 8,  LPS = 0, HT = 1056
                # VPS = 23, VPW = 10, VPS = 0, VT = 525
                #
                self.disp_x_size = 799
                self.disp_y_size = 479
                self.tft_io.tft_cmd_data_AS(0xe6, bytearray(b'\x05\x53\xf6'),
                                            3)  # PLL setting for PCLK
                # (33.3MHz * 1048576 / 100MHz) - 1 = 349174 = 0x553f6
                self.tft_io.tft_cmd_data_AS(
                    0xb0,
                    bytearray(  # # LCD SPECIFICATION
                        [
                            0x00,  # 18 Color bits, HSync/VSync low, No Dithering/FRC
                            0x00,  # TFT mode
                            self.disp_x_size >> 8,
                            self.disp_x_size & 0xff,  # physical Width of TFT
                            self.disp_y_size >> 8,
                            self.disp_y_size & 0xff,  # physical Height of TFT
                            0x00
                        ]),
                    7)  # Last byte only required for a serial TFT
                self.tft_io.tft_cmd_data_AS(
                    0xb4, bytearray(b'\x04\x1f\x00\x2e\x08\x00\x00\x00'), 8)
                # HSYNC,      Set HT 1056  HPS 46  HPW 8 LPS 0
                self.tft_io.tft_cmd_data_AS(
                    0xb6, bytearray(b'\x02\x0c\x00\x17\x08\x00\x00'), 7)
                # VSYNC,   Set VT 525  VPS 23 VPW 08 FPS 0
                self.tft_io.tft_cmd_data_AS(
                    0x36,
                    bytearray([(orientation & 1) << 5 | (h_flip & 1) << 1 |
                               (v_flip) & 1]), 1)
                # rotation/ flip, etc., t.b.d.
            elif lcd_type == "AT090TN10":  # Size 800x480, 9", 24 Bit, lower color bits ignored
                #
                # Value            Min     Typical   Max
                # DotClock       26.4 MHz 33.3 MHz  46.8 MHz
                # HT (Hor. Total   862     1056     1200
                # HDP (Hor. Disp)          800
                # HBP (back porch)  46      46       46
                # HFP (Fr. porch)   16     210      354
                # HPW (Hor. sync)   1                40
                # VT (Vert. Total) 510     525      650
                # VDP (Vert. Disp)         480
                # VBP (back porch)  23      23       23
                # VFP (fr. porch)   7       22      147
                # VPW (vert. sync)  1                20
                #
                # This table in combination with the relation above leads to the settings:
                # HPS = 46, HPW = 8,  LPS = 0, HT = 1056
                # VPS = 23, VPW = 10, VPS = 0, VT = 525
                #
                self.disp_x_size = 799
                self.disp_y_size = 479
                self.tft_io.tft_cmd_data_AS(0xe6, bytearray(b'\x05\x53\xf6'),
                                            3)  # PLL setting for PCLK
                # (33.3MHz * 1048576 / 100MHz) - 1 = 349174 = 0x553f6
                self.tft_io.tft_cmd_data_AS(
                    0xb0,
                    bytearray(  # # LCD SPECIFICATION
                        [
                            0x20,  # 24 Color bits, HSync/VSync low, No Dithering/FRC
                            0x00,  # TFT mode
                            self.disp_x_size >> 8,
                            self.disp_x_size & 0xff,  # physical Width of TFT
                            self.disp_y_size >> 8,
                            self.disp_y_size & 0xff,  # physical Height of TFT
                            0x00
                        ]),
                    7)  # Last byte only required for a serial TFT
                self.tft_io.tft_cmd_data_AS(
                    0xb4, bytearray(b'\x04\x1f\x00\x2e\x08\x00\x00\x00'), 8)
                # HSYNC,      Set HT 1056  HPS 46  HPW 8 LPS 0
                self.tft_io.tft_cmd_data_AS(
                    0xb6, bytearray(b'\x02\x0c\x00\x17\x08\x00\x00'), 7)
                # VSYNC,   Set VT 525  VPS 23 VPW 08 FPS 0
                self.tft_io.tft_cmd_data_AS(
                    0x36,
                    bytearray([(orientation & 1) << 5 | (h_flip & 1) << 1 |
                               (v_flip) & 1]), 1)
                # rotation/ flip, etc., t.b.d.
            else:
                print("Wrong Parameter lcd_type: ", lcd_type)
                return
            self.tft_io.tft_cmd_data_AS(0xBA, bytearray(b'\x0f'),
                                        1)  # GPIO[3:0] out 1
            self.tft_io.tft_cmd_data_AS(0xB8, bytearray(b'\x07\x01'),
                                        1)  # GPIO3=input, GPIO[2:0]=output

            self.tft_io.tft_cmd_data_AS(0xf0, bytearray(b'\x00'),
                                        1)  # Pixel data Interface 8 Bit

            self.tft_io.tft_cmd(0x29)  # Display on
            self.tft_io.tft_cmd_data_AS(0xbe,
                                        bytearray(b'\x06\xf0\x01\xf0\x00\x00'),
                                        6)
            # Set PWM for B/L
            self.tft_io.tft_cmd_data_AS(0xd0, bytearray(b'\x0d'),
                                        1)  # Set DBC: enable, agressive
        else:
            print("Wrong Parameter controller: ", controller)
            return
#
# Set character printing defaults
#
        self.text_font = None
        self.setTextStyle(self.color, self.BGcolor, 0, None, 0)
        #
        # Init done. clear Screen and switch BG LED on
        #
        self.text_x = self.text_y = self.text_yabs = 0
        self.clrSCR()  # clear the display
Example #52
0
    lcd.erase()
    if start_up == 0:
        lcd.set_pos(5, 2)
        lcd.write('Starting system...')
        loading = 0
        while loading < 100:
            lcd.set_pos(57, 20)
            lcd.write(str(loading))
            lcd.write('%')
            loading += randint(1, 10)
            if loading >= 100:
                loading = 100
                lcd.set_pos(55, 20)
                lcd.write(str(loading))
                lcd.write('%')
            pyb.delay(randint(200, 800))
            start_up = 1
    lcd.set_pos(40, 60)
    lcd.write('WELCOME')
    lcd.set_pos(25, 100)
    lcd.write('choose option')
    pyb.delay(5000)

    lcd.erase()
    t_choice = 0

    fg = lcd.rgb(255, 128, 128)

    lcd.set_pen(fg, lcd.rgb(0, 128, 0))
    lcd.rect(2, 2, 122, 78)
    lcd.set_pos(20, 40)
Example #53
0
 def __init__(self, pin_name):
     time.sleep(1)
     self.N1 = Pin(pin_name, Pin.OUT_PP)
     self.PinName = pin_name
     pyb.delay(10)
Example #54
0
    def __init__(self,
                 rs_pin,
                 enable_pin,
                 d0_pin=None,
                 d1_pin=None,
                 d2_pin=None,
                 d3_pin=None,
                 d4_pin=None,
                 d5_pin=None,
                 d6_pin=None,
                 d7_pin=None,
                 rw_pin=None,
                 backlight_pin=None,
                 num_lines=2,
                 num_columns=16):
        """Constructs the GpioLcd object. All of the arguments must be pyb.Pin
        objects which describe which pin the given line from the LCD is
        connected to.

        When used in 4-bit mode, only D4, D5, D6, and D7 are physically
        connected to the LCD panel. This function allows you call it like
        GpioLcd(rs, enable, D4, D5, D6, D7) and it will interpret that as
        if you had actually called:
        GpioLcd(rs, enable, d4=D4, d5=D5, d6=D6, d7=D7)

        The enable 8-bit mode, you need pass d0 through d7.

        The rw pin isn't used by this library, but if you specify it, then
        it will be set low.
        """
        self.rs_pin = rs_pin
        self.enable_pin = enable_pin
        self.rw_pin = rw_pin
        self.backlight_pin = backlight_pin
        self._4bit = True
        if d4_pin and d5_pin and d6_pin and d7_pin:
            self.d0_pin = d0_pin
            self.d1_pin = d1_pin
            self.d2_pin = d2_pin
            self.d3_pin = d3_pin
            self.d4_pin = d4_pin
            self.d5_pin = d5_pin
            self.d6_pin = d6_pin
            self.d7_pin = d7_pin
            if self.d0_pin and self.d1_pin and self.d2_pin and self.d3_pin:
                self._4bit = False
        else:
            # This is really 4-bit mode, and the 4 data pins were just
            # passed as the first 4 arguments, so we switch things around.
            self.d0_pin = None
            self.d1_pin = None
            self.d2_pin = None
            self.d3_pin = None
            self.d4_pin = d0_pin
            self.d5_pin = d1_pin
            self.d6_pin = d2_pin
            self.d7_pin = d3_pin
        self.rs_pin.init(Pin.OUT_PP)
        self.rs_pin.low()
        if self.rw_pin:
            self.rw_pin.init(Pin.OUT_PP)
            self.rw_pin.low()
        self.enable_pin.init(Pin.OUT_PP)
        self.enable_pin.low()
        self.d4_pin.init(Pin.OUT_PP)
        self.d5_pin.init(Pin.OUT_PP)
        self.d6_pin.init(Pin.OUT_PP)
        self.d7_pin.init(Pin.OUT_PP)
        self.d4_pin.low()
        self.d5_pin.low()
        self.d6_pin.low()
        self.d7_pin.low()
        if not self._4bit:
            self.d0_pin.init(Pin.OUT_PP)
            self.d1_pin.init(Pin.OUT_PP)
            self.d2_pin.init(Pin.OUT_PP)
            self.d3_pin.init(Pin.OUT_PP)
            self.d0_pin.low()
            self.d1_pin.low()
            self.d2_pin.low()
            self.d3_pin.low()
        if self.backlight_pin is not None:
            self.backlight_pin.init(Pin.OUT_PP)
            self.backlight_pin.low()

        # See about splitting this into begin

        delay(20)  # Allow LCD time to powerup
        # Send reset 3 times
        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET)
        delay(5)  # need to delay at least 4.1 msec
        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET)
        delay(1)
        self.hal_write_init_nibble(self.LCD_FUNCTION_RESET)
        delay(1)
        cmd = self.LCD_FUNCTION
        if not self._4bit:
            cmd |= self.LCD_FUNCTION_8BIT
        self.hal_write_init_nibble(cmd)
        delay(1)
        LcdApi.__init__(self, num_lines, num_columns)
        if num_lines > 1:
            cmd |= self.LCD_FUNCTION_2LINES
        self.hal_write_command(cmd)
Example #55
0
# boot.py -- runs on boot-up
# Select which scripts to run, with some extra logic
# > To run 'follow.py':
#       * press reset and do nothing else
# > To run 'dataread.py':
#       * press reset
#       * press user switch and hold until orange LED goes out

import pyb

orange = pyb.LED(3)  # create orange LED object
orange.on()  # indicate we are waiting for switch press
pyb.delay(2000)  # wait for user to maybe press the switch
switch = pyb.Switch()  # create switch object
switch_val = switch()  # sample the switch at end of delay
orange.off()  # indicate that we finished waiting for the switch
blue = pyb.LED(4)  # create blue LED object
blue.on()  # indicate that we are selecting the mode

if switch_val:
    pyb.usb_mode('CDC+MSC')
    pyb.main('dataread.py')  # if switch was pressed, run this
else:
    pyb.usb_mode('CDC+HID')
    pyb.main('pitlStage1.py')  # if switch wasn't pressed, run this

blue.off()  # indicate that we finished selecting the mode
Example #56
0
def main() :
  telemeter = HCSR04('X11', 'X12')
  
  while True :
    print('D:', telemeter.measure(), 'cm')
    pyb.delay(500)
Example #57
0
# http://forum.micropython.org/viewtopic.php?f=5&t=195&p=873&hilit=lcd_gfx#p873

import pyb
from ssd1306 import SSD1306
import lcd_gfx

oled = SSD1306(pinout={'dc': 'X4', 'res': 'X3'}, height=64, external_vcc=False)

oled.poweron()
oled.init_display()

oled.clear()
## text
oled.text('Hello World!', 20, 55)
oled.display()
pyb.delay(2000)

## draw straight lines
for x in [0, 127]:
    for y in range(64):
        oled.pixel(x, y, True)
for y in [0, 47, 48, 63]:
    for x in range(127):
        oled.pixel(x, y, True)

oled.display()
pyb.delay(2000)

## whole buffer
b = [1] * 1024
for i in range(0, 1024, 16):
Example #58
0
    def dealWithBroadcastREQ(self, srcId, payload, dataPacket):

        # Start reading the sensor if the data packet is not given (new transmission)
        # mainloop is responsible for initiating sensor data acquisition and processing now.
        # if not dataPacket:
        #    self.sensor.start_acquisition()
        # Note the time of receiving this packet
        reqTime = utime.ticks_ms()

        # If this is the first broadcast REQ of the frame, note the frame start time
        reqIndex = struct.unpack('B', payload[3:4])[0]

        # Update the start of frame time
        self.timeTillNextFrame = struct.unpack('I', payload[4:8])[0]
        self.ttnfTimestamp = reqTime  # note the time stamp for this TTNF

        # Check if I need to go back to always-on state after this
        sleepFlag = struct.unpack('B', payload[8:9])[0]

        # Decode the addresses of nodes expected to respond
        destAddr = list()
        for n in range(10, len(payload)):
            addr = struct.unpack('B', payload[n:n + 1])[0]
            destAddr.append(int(addr))

        # Respond only if I am in the list
        if self.thisNode in destAddr:

            # Print message for debugging
            print("REQ received from Node " + str(srcId))
            print("  Time till next frame: " + str(self.timeTillNextFrame) +
                  " msec")

            # If this is a request for location, put it into the payload
            if payload[9:10] == b'L':
                # Create the data payload
                dataPayload = b'L' + struct.pack(
                    'f', self.location[0]) + b'L' + struct.pack(
                        'f', self.location[1])
                packetPayload = b'UND' + struct.pack(
                    'B', self.thisNode) + dataPayload

            # Otherwise, this is a request for sensor readings
            else:
                # Read the sensor and create the data payload
                try:
                    if not dataPacket:
                        # mainloop is responsible for initiating sensor data acquisition and processing now.
                        # self.sensor.process_acquisition()
                        dataPayload = self.sensor.get_latest_data_as_bytes()
                        packetPayload = b'UND' + struct.pack(
                            'B', self.thisNode) + dataPayload
                    else:
                        packetPayload = dataPacket
                except Exception as e:
                    # If an Exception was caught, print the error
                    print("Error reading the sensor: " + str(e))
                    packetPayload = b'UND' + struct.pack(
                        'B', self.thisNode) + b'sensor_error'

            # Sleep for the remaining part of the transmit delay
            timeElapsed = utime.ticks_diff(utime.ticks_ms(), reqTime)
            if (self.txDelay > timeElapsed):
                pyb.delay(self.txDelay - timeElapsed)

            # Transmit the payload packet to the master node
            self.nm.send_unicast_message(srcId, packetPayload)

            # Print this transmission
            if payload[9:10] == b'L':
                print("Location data sent: Lat=" + '%.5f' % self.location[0] +
                      ", Long=" + '%.5f' % self.location[1])
            else:
                print("Sensor readings sent")

            # If I have any child nodes, do not go to sleep after this REQ
            if self.isRelay:
                sleepFlag = 0

            # Wait for a retransmission request, if one arrives (10 sec timeout)
            reTxTimeout = 10000
            timerStart = utime.ticks_ms()
            while utime.ticks_diff(utime.ticks_ms(),
                                   utime.ticks_add(timerStart,
                                                   reTxTimeout)) < 0:

                # Feed the watchdog
                if self.wdt:
                    self.wdt.feed()

                # Check if a packet has been received
                self.nm.poll_receiver()
                self.nm.process_incoming_buffer()
                if self.nm.has_received_packet():

                    # Read the incoming packet and see if it is a REQ
                    packet = self.nm.get_received_packet()
                    payload = bytes(packet.packet_payload)
                    srcId = packet.source_address
                    pktType = packet.packet_type
                    # If it is a REQ, process it by calling this function again
                    if (pktType
                            == 'B') and (len(payload) > 5) and (payload[0:3]
                                                                == b'UNR'):
                        # But if this is a broadcast REQ not from my master node, ignore it
                        if (srcId == self.masterNode):
                            canGoToSleep = self.dealWithBroadcastREQ(
                                srcId, payload, packetPayload)
                            sleepFlag = 1 if (
                                canGoToSleep
                            ) else 0  # Convert the sleep flag (due to recursion here!)
                            break  # finish waiting, the protocol has moved on
                    # If it is a unicast REQ, data transmission was successful, move on to relaying
                    elif (pktType
                          == 'U') and (len(payload) > 4) and (payload[0:3]
                                                              == b'UNR'):
                        canGoToSleep = self.dealWithUnicastREQ(payload)
                        sleepFlag = 1 if (
                            canGoToSleep
                        ) else 0  # Convert the sleep flag (due to recursion here!)
                        break  # finish waiting, the protocol has moved on
                    # Otherwise, pass it up to the main packet handling function
                    else:
                        (canGoToSleep, _,
                         pktIgnored) = self.handle_packet(packet)[0]
                        if not pktIgnored:
                            sleepFlag = 1 if (
                                canGoToSleep
                            ) else 0  # Convert the sleep flag (due to recursion here!)
                            break

        # Return the flag indicating if I can go to sleep or should stay awake
        return (sleepFlag == 1)
Example #59
0
    # full off and then back again.
    if PwmDirection == PWM_COUNT_DOWN:
        DutyCycle -= DUTY_CYCLE_CHANGE_RATE

        if DutyCycle <= LED_FULL_ON:
            PwmDirection = PWM_COUNT_UP
    else:
        DutyCycle += DUTY_CYCLE_CHANGE_RATE

        if DutyCycle >= LED_FULL_OFF:
            PwmDirection = PWM_COUNT_DOWN

    # This is a simple "State Machine" that will run different
    # colors and patterns based on how many times the button
    # has been pressed
    try:
        if System_State == 0:
            RGB_Button.RGB.Write(DutyCycle, LED_FULL_OFF, LED_FULL_OFF)
        elif System_State == 1:
            RGB_Button.RGB.Write(LED_FULL_OFF, DutyCycle, LED_FULL_OFF)
        elif System_State == 2:
            RGB_Button.RGB.Write(LED_FULL_OFF, LED_FULL_OFF, DutyCycle)
        elif System_State == 3:
            RGB_Button.RGB.Write(DutyCycle, DutyCycle, DutyCycle)
    except Exception as e:
        sys.print_exception(e)

    # This sets a periodic delay so that the DutyCycle doesn't
    # change too fast
    pyb.delay(25)
Example #60
0
# Create peripheral objects
b_LED = LED(4)
pot = ADC(Pin('X11'))

# I2C connected to Y9, Y10 (I2C bus 2) and Y11 is reset low active
oled = OLED_938(pinout={
    'sda': 'Y10',
    'scl': 'Y9',
    'res': 'Y8'
},
                height=64,
                external_vcc=False,
                i2c_devid=61)
oled.poweron()
oled.init_display()

# Simple Hello world message
oled.draw_text(0, 0, 'Hello, world!')  # each character is 6x8 pixels

tic = pyb.millis()  # store starting time
while True:
    b_LED.toggle()
    toc = pyb.millis()  # read elapsed time
    oled.draw_text(0, 20, 'Delayed time:{:6.3f}sec'.format(
        (toc - tic) * 0.001))
    oled.draw_text(0, 40, 'POT5K reading:{:5d}'.format(pot.read()))
    tic = pyb.millis()  # start time
    oled.display()
    delay = pyb.rng() % 1000  # Generate a random number btw 0 and 999
    pyb.delay(delay)  # Delay in milliseconds