Exemple #1
0
    def xbee_device(self):
        xbee_tx = self.cfg('pins_devices')['xbee_uart_tx']
        xbee_rx = self.cfg('pins_devices')['xbee_uart_rx']

        try:
            uart_xbee = UART(1, 115200, tx=xbee_tx, rx=xbee_rx)
            uart_xbee.init(9600,
                           bits=8,
                           parity=None,
                           stop=1,
                           tx=xbee_tx,
                           rx=xbee_rx)

            uart_xbee.write(b'+++')

            now = int(time.ticks_ms() / 1000)
            while True:

                if int(time.ticks_ms() / 1000) > now + 5:
                    print("[device] xbee-response \t\t\t[FAILED/TIMEOUT]")
                    return None

                recv = uart_xbee.read(-1)
                if (recv == None):
                    continue
                if (recv == b'OK\r'):
                    print("[device] xbee-response \t\t\t[OK]")
                    return uart_xbee

        except Exception as e:
            print("Error in xbee-init: " + str(e))
Exemple #2
0
def main():
    uart = UART(0, 115200)
    suc = False
    with open("file_name.py", "wb") as f:
        while True:
            data = read_timeout(uart, 2)
            if not data or data[0] != ord("#"):
                x = uart.write(b"#2")
                break
            count = data[1]
            if count == 0:
                suc = True
                break
            data = read_timeout(uart, count)
            if data:
                esc = False
                for c in data:
                    if c == 0:
                        esc = True
                        continue
                    x = f.write(bytes([c & 0x0F if esc else c]))
                    esc = False
                x = uart.write(b"#1")
            else:
                x = uart.write(b"#3")
                break
    x = uart.write(b"#1#" if suc else b"#0#")
class UartCom:
	def __init__(self):
		self.uart = UART(1, 9600)
		self.uart.init(9600, bits = 8, parity=None, stop=1, rx=35, tx = 32, timeout=5000)

	def send_Message(self, message):
		self.uart.write(message)
		time.sleep_ms(5)		
Exemple #4
0
class MHZ19BSensor:

    # initializes a new instance
    def __init__(self, tx_pin, rx_pin, lights, co2_threshold):
        self.uart = UART(1,
                         baudrate=9600,
                         bits=8,
                         parity=None,
                         stop=1,
                         tx=int(tx_pin),
                         rx=int(rx_pin))
        self.lights = lights
        self.co2_threshold = int(co2_threshold)

    # measure CO2
    def measure(self):
        while True:
            # send a read command to the sensor
            self.uart.write(b'\xff\x01\x86\x00\x00\x00\x00\x00\x79')

            # a little delay to let the sensor measure CO2 and send the data back
            time.sleep(1)  # in seconds

            # read and validate the data
            buf = self.uart.read(9)
            if self.is_valid(buf):
                break

            # retry if the data is wrong
            self.lights.error_on()
            print('error while reading MH-Z19B sensor: invalid data')
            print('retry ...')

        self.lights.error_off()

        co2 = buf[2] * 256 + buf[3]
        print('co2         = %.2f' % co2)

        # turn on the LED if the CO2 level is higher than the threshold
        if co2 > self.co2_threshold:
            self.lights.high_co2_on()
        else:
            self.lights.high_co2_off()

        return [co2]

    # check data returned by the sensor
    def is_valid(self, buf):
        if buf is None or buf[0] != 0xFF or buf[1] != 0x86:
            return False
        i = 1
        checksum = 0x00
        while i < 8:
            checksum += buf[i] % 256
            i += 1
        checksum = ~checksum & 0xFF
        checksum += 1
        return checksum == buf[8]
Exemple #5
0
def getCO2():
    uart = UART(1, 9600, rx=15, tx=12)

    uart.init(9600, bits=8, parity=None, stop=1, timeout=200)

    uart.write(b'\xff\x01\x86\x00\x00\x00\x00\x00y')
    s = uart.readline(9)

    return ((s[2] * 256) + s[3])
Exemple #6
0
class TC():
    def __init__(self, uart=2, baudrate=9600):
        self.u = UART(uart, baudrate)  #

    def send(self, text):
        self.u.write(text)

    def recv(self):
        return self.u.read()
Exemple #7
0
class DYPlayer():
    """DY-SV17F模块驱动
        使用ESP8266上的UART1中TX端口发送控制指令
        使用Flash
    """
    def __init__(self):
        self._uart = UART(1, 9600)

    def set_play_model(self, play_model=_PLAY_MODEL_SINGLE_LOOP):
        """设置循环模式"""
        self._send_command(bytearray([0x18, 0x01, play_model]))

    def set_loop_num(self, loop_num=30):
        """设置循环次数
            指令:AA 19 02 次数高 次数低 SM
        """
        h_value = loop_num & 0b1111111100000000
        l_value = loop_num & 0b0000000011111111
        self._send_command(bytearray([0x19, 0x02, h_value, l_value]))

    def _get_sm(self, buff):
        """获取和检验
            为之前所有字节之和的低8位,即起始码到数据相加后取低8位。
        """
        value = 0

        for i in range(len(buff)):
            value += buff[i]

        return value & 0b0000000011111111

    def _send_command(self, cmd_buff):
        """发送指令给模块"""
        cmd_buff = bytearray([0xaa]) + cmd_buff
        sm = self._get_sm(cmd_buff)
        self._uart.write(cmd_buff + bytearray([sm]))

    def set_volume(self, num):
        """音量设置"""
        self._send_command(bytearray([0x13, 0x01, num]))

    def play(self, single_name="/00001.mp3"):
        """播放指定盘符指定路径的文件"""
        single_name = single_name.replace(".", "*").upper()
        buff = bytearray(3 + len(single_name))
        buff[0] = 0x08
        buff[1] = len(single_name) + 1
        buff[2] = _DISK_FLASH

        for i in range(len(single_name)):
            buff[3 + i] = ord(single_name[i])

        self._send_command(buff)

    def stop(self):
        """停止"""
        self._send_command(bytearray([0x04, _PLAY_STATUS_STOP]))
Exemple #8
0
class MHZ14A():
    read_packet = [0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79]

    def __init__(self, uartNum=1, txPin=18, rxPin=19):
        """initializes communication with CO2 sensor"""
        self.uart = UART(uartNum, 9600)
        self.uart.init(parity=None, stop=1, bits=8, rx=rxPin, tx=txPin)
        # wait a minimum amount of time before trying to read the sensor
        sleep_ms(250)

    def send_command(self, packet):
        # flush serial
        while self.uart.any() > 0:
            self.uart.read(self.uart.any())
        # send packet
        self.uart.write(bytearray(packet))

    def readCO2(self):
        """reads CO2 concentration from MH-Z14a sensors and returns ppm value"""
        read_packet = [0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79]
        try:
            self.send_command(read_packet)
            start = ticks_ms()
            while self.uart.any() < 9:
                if ticks_diff(ticks_ms(), start) > 5000:
                    print("Timeout reading CO2 sensor")
                    return -4
            res = self.uart.read(9)
            if res is not None and len(res) == 9:
                checksum = 0xff & (~(res[1] + res[2] + res[3] + res[4] +
                                     res[5] + res[6] + res[7]) + 1)
                if res[8] == checksum:
                    res = bytearray(res)
                    ppm = (res[2] << 8) | res[3]
                    return ppm
                else:
                    print("CO2 sensor reading checksum failed. Result was: ",
                          res)
                    return -1
            else:
                print("CO2 sensor did not return data")
                return -2
        except Exception as e:
            print("Exception reading sensor:")
            print(str(e))
            return -3

    def zeroPointCalibration(self):
        """Starts a zero point calibration"""
        zpc_packet = [0xFF, 0x01, 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79]
        try:
            self.send_command(zpc_packet)
        except Exception as e:
            print("Exception calibrating sensor:")
            print(str(e))
            return -3
class mhz19:
    def __init__(self, uart_no):
        self.uart_no = uart_no
        self.start()
        self.ppm = 0
        self.temp = 0
        self.co2status = 0

    def start(self):
        self.uart = UART(self.uart_no, 9600)
        self.uart.init(9600, bits=8, parity=None, stop=1, timeout=10)

    def stop(self):
        while self.uart.any():
            self.uart.read(1)
        self.uart.deinit()

    def get_data(self):
        self.uart.write(b"\xff\x01\x86\x00\x00\x00\x00\x00\x79")
        time.sleep(0.1)
        s = self.uart.read(9)
        try:
            z = bytearray(s)
        except:
            return 0
        # Calculate crc
        crc = self.crc8(s)
        if crc != z[8]:
            # we should restart the uart comm here..
            self.stop()
            time.sleep(1)
            self.start()

            print(
                'CRC error calculated %d bytes= %d:%d:%d:%d:%d:%d:%d:%d crc= %dn'
                % (crc, z[0], z[1], z[2], z[3], z[4], z[5], z[6], z[7], z[8]))
            return 0
        else:
            self.ppm = ord(chr(s[2])) * 256 + ord(chr(s[3]))
            self.temp = ord(chr(s[4])) - 40
            self.co2status = ord(chr(s[5]))
            return 1

    def crc8(self, a):
        crc = 0x00
        count = 1
        b = bytearray(a)
        while count < 8:
            crc += b[count]
            count = count + 1
        # Truncate to 8 bit
        crc %= 256
        # Invert number with xor
        crc = ~crc & 0xFF
        crc += 1
        return crc
Exemple #10
0
def usb_serial_comm():
    import utime
    from machine import UART

    #u = UART(0, baudrate=115200)
    u = UART(0)
    u.write(b'START\n')
    for i in range(0, 10):
        s = 'DATA:{{"i":{}}}\n'.format(i)
        u.write(bytearray(s))
        utime.sleep_ms(1000)
Exemple #11
0
def usb_serial_ticks():
    import utime
    from machine import UART
    from encoder import DualHallEncoder

    u = UART(0, baudrate=115200)
    u.write(b'START\n')
    e = DualHallEncoder(h1, h2)
    while True:
        if e.detect_tick():
            u.write(bytearray('DATA:{{"ticks":{}}}\n'.format(e.ticks)))
Exemple #12
0
def run():
    print('demo UART')
    adc = ADC(Pin(32))
    uart = UART(2, baudrate=9600)  # tx2 rx2
    T = 0
    while 1:
        T = (24 * (adc.read()) * 3.3 / 4096)
        uart.write('La temperatura es: ' + str(T) + ' C' + '\r\n')
        string = uart.read()
        print("%s" % (string))
        time.sleep(2)
Exemple #13
0
class Mp3:
    def __init__(self, volume_level=15):
        self.uart = UART(2, baudrate=9600, rx=25, tx=32, timeout=10)
        self.volume_level = volume_level

    def play_track(self, track_id):
        self.uart.write(cmd.play_track(track_id))

    def set_volume(self, level):
        self.volume_level = level
        self.uart.write(cmd.set_volume(level))
Exemple #14
0
def uartWrite():
    count = 10
    # 配置uart
    uart = UART(UART.UART1, 115200, 8, 0, 1, 0)
    while count:
        write_msg = "Hello count={}".format(count)
        # 发送数据
        uart.write(write_msg)
        uart_log.info("Write msg :{}".format(write_msg))
        utime.sleep(1)
        count -= 1
    uart_log.info("uartWrite end!")
Exemple #15
0
class ESPOut(retune.Retuner):
    def init_esp(self):
        self.loop = True
        self.midiout = UART(0, 31250)
        self.midiout.init(31250)
        exit_pin = Pin(15, Pin.IN)
        exit_pin.irq(trigger=Pin.IRQ_FALLING, handler=self.exit_event)

    def output(self, mess):
        self.midiout.write(bytes(mess))

    def exit_event(self, p):
        self.loop = False
Exemple #16
0
class UartLights:
    '''Used to write LED color as 3 RGB bytes over a serial link'''
    def __init__(self, pixelCount=16, baud=115200, bytesPerPixel = 3):
        assert pixelCount < 256 # a single byte is used to set the pixelcount
        self.uart = UART(1, baud)
        self.header = bytes([pixelCount])   # set the leading byte to be permanently the pixelCount
        self.buffer = bytearray(pixelCount * bytesPerPixel) # a byte each for red, green, blue
        self.footer = bytes([ord('\n')])    # set the trailing byte to be permanently newline

    def sendColorBytes(self):
        self.uart.write(self.header)
        self.uart.write(self.buffer)
        self.uart.write(self.footer)
Exemple #17
0
class Serial:
    """ simple class to constantly read and write serial data
        for test purposes only"""
    def __init__(self, baudRate=115200):
        self.baudRate = baudRate
        print("here")
        # the next line creates the uart object and sets uart 1 to be used with pins
        # 1 and 3, which are normally dedicated to uart 0 and locked to REPL.
        # with this code we bypass that and allow communication via the USB cable

        self.uart = UART(1,
                         tx=1,
                         rx=3,
                         baudrate=self.baudRate,
                         bits=8,
                         parity=None,
                         stop=1)

        self.uart.init()

    def writeData(self, data2Write="m"):
        """write data to port without considering if there is anyone listening on the other side"""
        self.uart.write(data2Write)
        return

    def readData(self):
        if self.uart.any() > 0:
            self.uart.readline()

    def readDataPoll(self, timeout=100):  # amount2Read=0):
        """use poll method to see how many characters are available for reading, 
        read them, and return it
        OBS: need to learn what is the UART buffer size and implement controls on the PC side"""
        poll = uselect.poll()
        poll.register(self.uart, uselect.POLLIN)
        # set the duration for waiting
        poll.poll(timeout)

        # timeout=-1 polls the port indefintely. poll.poll returns  a list of tuples that need to be worked on
        amount2read = poll.poll()
        amount2read = (
            amount2read[0][1] + 4
        )  # +4 reads the trailing "/n/r" at the end of each line

        data = self.uart.read(amount2read)

        # print(data)
        # add if statement to make use of poll
        # readData = self.uart.read(amount2Read)
        # print(readData)
        return data
Exemple #18
0
class GPS:
    def __init__(self, tx, rx):
        self.tx = tx
        self.rx = rx
        self.uart = UART(1, baudrate=9600, tx=self.tx, rx=self.rx)

        # parameters
        self.latitude = 0
        self.longitude = 0
        self.speed = 0
        self.heading = 0

        # Setup commands - turn off automatic messages
        self.write("$PUBX,40,GGA,0,0,0,0")
        self.write("$PUBX,40,GLL,0,0,0,0")
        self.write("$PUBX,40,GSA,0,0,0,0")
        self.write("$PUBX,40,GSV,0,0,0,0")
        self.write("$PUBX,40,VTG,0,0,0,0")
        self.write("$PUBX,40,ZDA,0,0,0,0")

        tx_pin = Pin(tx, Pin.OUT)
        rx_pin = Pin(rx, Pin.IN)
        # If pin is changing, check
        self.buffer = bytearray()
        #rx_pin.irq(handler=self.update, trigger=Pin.IRQ_RISING)

    def write(self, msg):
        # Find checksum without $ character
        check = self.checksum(msg[1:])

        # Reconstruct string with checksum
        out = "{}*{}\r\n".format(msg, hex(check)[2:])
        self.uart.write(out)
        #print(out)

    def checksum(self, msg):
        # checksum is xor of each byte between $ and *
        check = 0
        for el in msg:
            # xor the hex value of each element found with ord() function
            check ^= ord(el)

        return check

    #def update(self, pin):
    def update(self):
        # $GPRMC, hhmmss.ss, Status, Latitude, N/S, Longitude, E/W, Spd, Cog,
        #         date, mv, mvE/W, mode, cs, \r\n
        if self.uart.any() >= 2:
            reading = bytearray(self.uart.read())
            print(reading)
Exemple #19
0
class Sigfox(object):
    def __init__(self):
        uos.dupterm(None, 1)
        self.uart = UART(0, 9600)
        self.uart.init(9600, bits=8, parity=None, stop=1)

    def wait_for(self, success, failure, timeout):
        """Wait for a response
        Args:
            success: success message
            failure: failure message
            timeout: timeout in seconds
        """
        iter_count = timeout / 0.1
        success_h = ubinascii.hexlify(success).decode('utf-8')
        failure_h = ubinascii.hexlify(failure).decode('utf-8')
        message = ""

        while (iter_count >= 0 and success_h not in message
               and failure_h not in message):
            if self.uart.any() > 0:
                c = self.uart.read()
                hex_str = ubinascii.hexlify(c).decode("utf-8")
                message += hex_str
            iter_count -= 1
            sleep(0.1)
        if success_h in message:
            return message
        elif failure_h in message:
            print("Failure ({})".format(message.replace('\r\n', '')))
        else:
            print("Received timeout ({})".format(message.replace('\r\n', '')))
        return ''

    def test_connection(self, timeout=3):
        print('testing connection')
        self.uart.write("AT\r")
        if self.wait_for('OK', 'ERROR', timeout):
            return 'connection ok'
        else:
            return ''

    def send_message(self, message):
        res = ''
        while not res:
            res = self.test_connection(timeout=1)
        print('connection ok, sending message')
        self.uart.write("AT$SF={}\r".format(message))
        if self.wait_for('OK', 'ERROR', 15):
            print('Message send')
Exemple #20
0
def init():
    global raw_uart, baudrate
    raw_uart = UART(1, tx=TX_PIN, rx=RX_PIN)
    raw_uart.init(baudrate=baudrate,
                  bits=8,
                  parity=None,
                  stop=1,
                  tx=TX_PIN,
                  rx=RX_PIN,
                  txbuf=TXBUF_LEN,
                  rxbuf=RXBUF_LEN,
                  timeout=READ_TIMEOUT,
                  timeout_char=WRITE_WAIT)
    raw_uart.write('\r\n# UART initialised\r\n')
    return raw_uart
Exemple #21
0
class MidiInterface:
    baud = 31250

    def __init__(self):
        self.uart = None

    def connect(self):
        self.uart = UART(2, self.baud)
        self.uart.init(self.baud, bits=8, parity=None, stop=1, tx=18)

    def send(self, slot):
        if midi_messages.slots.messages[slot] and self.uart:
            message = midi_messages.slots.pop_message(slot)
            self.uart.write(bytes(message))
            print('Sent {}'.format(message))
Exemple #22
0
 def writeCommand(self, command):
     output = command + '\r\n'
     uart = UART(1,
                 baudrate=9600,
                 pins=(Pin.exp_board.G9, Pin.exp_board.G8))
     uart.write(output)
     #wait max 3(s) for output from the sensor
     waitcounter = 0
     while (waitcounter < 5 and not uart.any()):
         time.sleep(0.5)
         waitcounter += 1
     response = uart.readall()
     uart.deinit()
     print(response)
     return (response)
class ArduinoConn():
    _STX = 0x02
    _ETX = 0x03

    @staticmethod
    def _startRecvThread(func, args):
        print("_startRecvThread")
        start_new_thread(func, args)

    def __init__(self, id=2, baud=115200):
        self._uart = UART(id, baud)

    def init(self, txPin=None, rxPin=None):
        self._uart.init(tx=txPin, rx=rxPin)

    def startRecvThread(self, callback):
        print("startRecvThread")
        ArduinoConn._startRecvThread(self._recv, (callback, ))
        print("startRecvThread end")

    def send(self, message):
        buf = bytearray(chr(ArduinoConn._STX)) + bytearray(
            message.encode()) + bytearray(chr(ArduinoConn._ETX))
        self._uart.write(buf)

    def _recv(self, callback):
        tele = ArduinoTele()
        poller = select.poll()
        poller.register(self._uart, select.POLLIN)

        while True:
            events = poller.poll()
            print('events =', events)
            while self._uart.any():
                buf = self._uart.read(1)
                print(buf)
                if buf[0] == ArduinoConn._STX:
                    print("-> STX")
                    tele.clear()
                    tele.isRecving = True
                elif buf[0] == ArduinoConn._ETX:
                    print("-> ETX")
                    if tele.isRecving:
                        print(tele.data)
                        callback(tele)
                        tele.clear()
                elif tele.isRecving:
                    tele.data += buf.decode()
class LCD:
    def __init__(self, tx_pin=1, baud_rate=19200, backlight=1):
        utime.sleep_ms(100)
        self.uart = UART(tx_pin, baud_rate)
        # 22 for no cursor, 23 for cursor off and flashing block, 24 for flat horizontal, 25 for flashing block
        self.setCursorType(22)
        self.backlight(backlight)
        self.clearScreen()

    def write(self, string):
        self.uart.write(str(string))

    def clearScreen(self):
        self.write('\f')
        utime.sleep_ms(5)

    def cursorLeft(self):
        self.write('\b')

    def cursorRight(self):
        self.write('\t')

    def newLine(self):
        self.write('\n')

    def carriageReturn(self):
        self.write('\r')

    def display(self, state):
        if(state):
            self.write(chr(self.cursor_type))
        else:
            self.write(chr(21))

    def setCursorType(self, cursor_type):
        self.cursor_type = cursor_type
        self.write(chr(self.cursor_type))

    def goto(self, location=0):
        # 128-217
        home = 128
        self.write(chr(home + location))

    def backlight(self, state):
        if(state):
            self.write(chr(17))
        else:
            self.write(chr(18))
Exemple #25
0
def UARTtransmission():

    uart1 = UART(0, 115200, bits=8, parity=None, stop=1)
    uart1.init(baudrate=115200, bits=8, parity=None, stop=1)

    SLEEP = 0.03
    data1 = ''
    fileName = ''
    send = ''

    while True:
        if (uart1.any()):
            pycom.rgbled(0xFF0000)  # set LED to RED
            data = uart1.readall().decode(
                'utf-8')  # recieves data and decodes from utf-8

            if data != data1 and str(data[:3]) == str("{0:0=3d}".format(
                    len(data))):

                if data[3:13] == 'filename: ':  #new fileName
                    fileName = data[13:]
                    fileWrite = open(fileName, 'w').close()  #clear ever$

                elif data[3:] == 'Finish':  #finished message
                    fileName = ''
                    pycom.rgbled(0xFFFFFF)  # set LED to WHITE

                else:  # writes inside of the file
                    data = data[3:]
                    fileWrite = open(fileName, 'a')  #opens to write insi$
                    fileWrite.write(data)  #writes inside the data
                    fileWrite.close()  #close file
                    data1 = data
                    print(data1)

                uart1.write(
                    bytes('received', 'utf-8'
                          ))  #sends back a message to notify that was recieved
                time.sleep(SLEEP)

            elif data == data1:
                uart1.write(
                    bytes('received', 'utf-8'
                          ))  #sends back a message to notify that was recieved
                time.sleep(SLEEP)
            else:
                pycom.rgbled(0xFFFFFF)  # set LED to WHITE
                time.sleep(SLEEP)
Exemple #26
0
class DOUBLE_GPS(object):
    GGA_MESSAGE = b"$GPGGA,141623.523,2143.963,S,04111.493,W,1,12,1.0,0.0,M,0.0,M,,*65\n"
    RMC_MESSAGE = b"$GPRMC,141623.523,A,2143.963,S,04111.493,W,,,301019,000.0,W*7B\n"
    UPDATE_RATE_1S = 'PMTK220,1000'

    def __init__(self, TX, RX, uart):
        self.uart = UART(uart, baudrate=9600)
        self.uart.init(9600, bits=8, tx=TX, rx=RX)
        self.flag = False

    def make_data_available(self, NMEA_sentence):
        self.uart.write(NMEA_sentence)

    def received_command(self):
        command = self.uart.readline()
        if (command != None):
            command, received_check_sum = command.split(b'*')
            command = command.strip(b'$')
            received_check_sum = received_check_sum[0:2]
            generated_check_sum = self.generate_checksum(command)
            command = command.decode()
            if command == self.UPDATE_RATE_1S:
                self.continuous_mode()
                self.flag = True
            return command
        else:
            return None

    def generate_checksum(self, command):
        checksum = 0
        for char in command:
            checksum ^= char
        return checksum

    def continuous_mode(self):
        self.my_timer = Timer(1)
        self.my_timer.init(period=1000,
                           mode=self.my_timer.PERIODIC,
                           callback=self.my_callback)

    def my_callback(self, timer):
        self.make_data_available(self.RMC_MESSAGE)

    def deinit(self):
        self.uart.deinit()
        if hasattr(self, 'my_timer'):
            self.my_timer.deinit()
Exemple #27
0
class IRTrans(object):
    """
    红外发射模块

    :param tx: 发送引脚设置
    :param uart_id: 串口号:1、2
    """
    def __init__(self, tx, uart_id=2):
        self.uart = UART(uart_id, baudrate=115200, tx=tx)

    def transmit(self, byte):
        """
        发送数据

        :param byte byte: 发送数据,单字节
        """
        self.uart.write(byte)
Exemple #28
0
class GetLp:
    """
    通过向板载噪声模块发送问询帧,获取测量数据
    """
    query = bytearray([0x01,0x03,0x00,0x00,0x00,0x01,0x84,0x0A])
    def __init__(self):
        from machine import UART
        self.uart = UART(2, 9600)

    def get_value(self):
        val = self.uart.read()
        self.uart.write(self.query)
        if val != None:
            val = int('0x' + hex(val[3])[2:] + hex(val[4])[2:])
            return val / 10
        else:
            return False
class RFID:
    def __init__(self,
                 rx=15,
                 tx=2,
                 freq=1,
                 new_tag_cmd=None,
                 tag_removed_cmd=None):
        self.uart = UART(1, tx=tx, rx=rx, baudrate=115200)
        self.uart.init()
        self.uart.write(b'\xAB\xBA\x00\x10\x00\x10')
        #self.uart.read()#clear buffer
        self.uart.flush()
        self.uart.any()
        self.new_tag_cmd = new_tag_cmd
        self.tag_removed_cmd = tag_removed_cmd

        self.current_id = b''
        self.waittime = max(.2, 1 / freq)
        self.uart.callback(UART.CBTYPE_PATTERN,
                           self.uart_cb,
                           pattern=b'\xcd\xdc')
        loop = asyncio.get_event_loop()
        loop.create_task(self.mainloop())

    def uart_cb(self, response):
        #print('[RFID] {}'.format(' '.join('{:02x}'.format(x) for x in  bytearray(response[2]))))
        response = bytearray(response[2])
        if response[:2] == b'\x00\x81':
            id = response[2:-1]
            if id != self.current_id:
                log.info('new card "{}"'.format(' '.join('{:02x}'.format(x)
                                                         for x in id)))
                self.current_id = id
                if self.new_tag_cmd is not None:
                    self.new_tag_cmd(id)
        elif self.current_id:
            log.info('card "{}" removed'.format(' '.join(
                '{:02x}'.format(x) for x in self.current_id)))
            if self.tag_removed_cmd is not None:
                self.tag_removed_cmd(self.current_id)
            self.current_id = b''

    async def mainloop(self):
        while True:
            self.uart.write(b'\xAB\xBA\x00\x10\x00\x10')
            await asyncio.sleep(self.waittime - .1)
Exemple #30
0
def do():
    killbits = [
        "M0 ", "041", "000", "000", "026", "200", "001", "016", "000", "032",
        "032", "032", "032", "011", "322", "010", "000", "333", "377", "172",
        "017", "127", "303", "010", "000", "X", "J0 "
    ]
    uart = UART(2, tx=17, rx=16, timeout=10)
    uart.init(9600)
    if uart.any():
        uart.read()  # flush
    print('Loading bitstream')
    iceboot.boot('altair.bin')
    print('Done')
    print(uart)
    for oword in killbits:
        uart.write(oword)
        utime.sleep_ms(100)
        while uart.any():
            print(uart.readline())
Exemple #31
0
class DeepSleep:

    WPUA_ADDR = const(0x09)
    OPTION_REG_ADDR = const(0x0E)
    IOCAP_ADDR = const(0x1A)
    IOCAN_ADDR = const(0x1B)

    WAKE_STATUS_ADDR = const(0x40)
    MIN_BAT_ADDR = const(0x41)
    SLEEP_TIME_ADDR = const(0x42)
    CTRL_0_ADDR = const(0x45)

    EXP_RTC_PERIOD = const(7000)

    def __init__(self):
        self.uart = UART(1, baudrate=10000, pins=(COMM_PIN, ))
        self.clk_cal_factor = 1
        self.uart.read()
        # enable the weak pull-ups control
        self.clearbits(OPTION_REG_ADDR, 1 << 7)

    def _send(self, data):
        self.uart.write(bytes(data))

    def _start(self):
        self.uart.sendbreak(20)
        self._send([0x55])

    def _magic(self, address, and_val, or_val, xor_val, expected=None):
        self._start()
        self._send([address, and_val & 0xFF, or_val & 0xFF, xor_val & 0xFF])
        if expected is None:
            return self.uart.read()
        else:
            if expected > 0:
                return self.uart.read(expected)

    def _add_to_pin_mask(self, mask, pin):
        if pin == 'P10' or pin == 'G17':
            mask |= 0x01
        elif pin == 'P17' or pin == 'G31':
            mask |= 0x02
        elif pin == 'P18' or pin == 'G30':
            mask |= 0x08
        else:
            raise ValueError('Invalid Pin specified: {}'.format(pin))
        return mask

    def _create_pin_mask(self, pins):
        mask = 0
        if type(pins) is str:
            mask = self._add_to_pin_mask(mask, pins)
        else:
            for pin in pins:
                mask = self._add_to_pin_mask(mask, pin)
        return mask & PIN_MASK

    def poke(self, address, value):
        self._magic(address, 0, value, 0)

    def peek(self, address):
        return self._magic(address, 0xFF, 0, 0)[6]

    def setbits(self, address, mask):
        self._magic(address, 0xFF, mask, 0)

    def clearbits(self, address, mask):
        self._magic(address, ~mask, 0, 0)

    def togglebits(self, address, mask):
        self._magic(address, 0xFF, 0, mask)

    def calibrate(self):
        """ The microcontroller will send the value of CTRL_0 after setting the bit
            and then will send the following pattern through the data line:

               val | 1 | 0 | 1*| 0 | 1*| 0 | 1
               ms  | 1 | 1 | 1 | 1 | 8 | 1 | -

            The idea is to measure the real life duration of periods marked with *
            and substract them. That will remove any errors common to both measurements
            The result is 7 ms as generated by the PIC LF clock.
            It can be used to scale any future sleep value. """

        # setbits, but limit the number of received bytes to avoid confusion with pattern
        self._magic(CTRL_0_ADDR, 0xFF, 1 << 2, 0, 0)
        self.uart.deinit()
        self._pulses = pycom.pulses_get(COMM_PIN, 50)
        self.uart = UART(1, baudrate=10000, pins=(COMM_PIN, ))
        try:
            self.clk_cal_factor = (self._pulses[4][1] - self._pulses[1][1]) / EXP_RTC_PERIOD
        except:
            pass
        if self.clk_cal_factor > 1.25 or self.clk_cal_factor < 0.75:
            self.clk_cal_factor = 1

    def enable_auto_poweroff(self):
        self.setbits(CTRL_0_ADDR, 1 << 1)

    def enable_pullups(self, pins):
        mask = self._create_pin_mask(pins)
        self.setbits(WPUA_ADDR, mask)

    def disable_pullups(self, pins):
        mask = self._create_pin_mask(pins)
        self.clearbits(WPUA_ADDR, mask)

    def enable_wake_on_raise(self, pins):
        mask = self._create_pin_mask(pins)
        self.setbits(IOCAP_ADDR, mask)

    def disable_wake_on_raise(self, pins):
        mask = self._create_pin_mask(pins)
        self.clearbits(IOCAP_ADDR, mask)

    def enable_wake_on_fall(self, pins):
        mask = self._create_pin_mask(pins)
        self.setbits(IOCAN_ADDR, mask)

    def disable_wake_on_fall(self, pins):
        mask = self._create_pin_mask(pins)
        self.clearbits(IOCAN_ADDR, mask)

    def get_wake_status(self):
        # bits as they are returned from PIC:
        #   0: PIN 0 value after awake
        #   1: PIN 1 value after awake
        #   2: PIN 2 value after awake
        #   3: PIN 3 value after awake
        #   4: TIMEOUT
        #   5: POWER ON

        wake_r = self.peek(WAKE_STATUS_ADDR)
        return {'wake': wake_r & (TIMER_WAKE | POWER_ON_WAKE),
                'P10': wake_r & 0x01, 'P17': (wake_r & 0x02) >> 1,
                'P18': (wake_r & 0x08) >> 3}

    def set_min_voltage_limit(self, value):
        # voltage value passed in volts (e.g. 3.6) and round it to the nearest integer
        value = int(((256 * 2.048) + (value / 2)) / value)
        self.poke(MIN_BAT_ADDR, value)

    def go_to_sleep(self, seconds):
        gc.collect()
        while True:
            try:
                self.calibrate()
            except Exception:
                pass

            # the 1.024 factor is because the PIC LF operates at 31 KHz
            # WDT has a frequency divider to generate 1 ms
            # and then there is a binary prescaler, e.g., 1, 2, 4 ... 512, 1024 ms
            # hence the need for the constant

            # round to the nearest integer
            seconds = int((seconds / (1.024 * self.clk_cal_factor)) + 0.5)
            self.poke(SLEEP_TIME_ADDR, (seconds >> 16) & 0xFF)
            self.poke(SLEEP_TIME_ADDR + 1, (seconds >> 8) & 0xFF)
            self.poke(SLEEP_TIME_ADDR + 2, seconds & 0xFF)
            self.setbits(CTRL_0_ADDR, 1 << 0)

    def hw_reset(self):
        self.setbits(CTRL_0_ADDR, 1 << 4)
Exemple #32
0
    global uart0_int_count
    if uart0_irq.flags() & UART.RX_ANY:
        uart0_int_count += 1


def uart1_handler(uart_o):
    global uart1_irq
    global uart1_int_count
    if uart1_irq.flags() & UART.RX_ANY:
        uart1_int_count += 1


uart0_irq = uart0.irq(trigger=UART.RX_ANY, handler=uart0_handler)
uart1_irq = uart1.irq(trigger=UART.RX_ANY, handler=uart1_handler)

uart0.write(b"123")
# wait for the characters to be received
while not uart1.any():
    pass

time.sleep_us(100)
print(uart1.any() == 3)
print(uart1_int_count > 0)
print(uart1_irq.flags() == 0)
print(uart0_irq.flags() == 0)
print(uart1.read() == b"123")

uart1.write(b"12345")
# wait for the characters to be received
while not uart0.any():
    pass
# freezing -> did we already send the sms ? don't send it twice
freezing = False

# set the clock
c = untplib.NTPClient()
rtclock = RTC()
clock_adjust()

# set the regex for the uart answers
re = ure.compile("\r\nOK\r\n")
er = ure.compile("\r\nERROR\r\n")

# config the uart and see if somethings answers
uart = UART(1, baudrate=115200, pins=(TX_PIN, RX_PIN))  # uart #, baudrate, pins tx,rx
uart.write('+++')
uart.write('AT+COPS?\r\n')
time.sleep(1)
while uart.any() != 0:
    print(uart.readall())

# get the battery
adc = ADC()
bat = adc.channel(pin=BAT_PIN)

# initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH, server=BLYNK_SERVER)

# register virtual pin 4 (the button on the blynk that sends the temp sms right away)
blynk.add_virtual_pin(4, write=v4_write_handler)
Exemple #34
0
uart = UART(baudrate=38400, pins=('GP12', 'GP13'))
print(uart)
uart = UART(pins=('GP12', 'GP13'))
print(uart)
uart = UART(pins=(None, 'GP17'))
print(uart)
uart = UART(baudrate=57600, pins=('GP16', 'GP17'))
print(uart)

# now it's time for some loopback tests between the uarts
uart0 = UART(0, 1000000, pins=uart_pins[0][0])
print(uart0)
uart1 = UART(1, 1000000, pins=uart_pins[1][0])
print(uart1)

print(uart0.write(b'123456') == 6)
print(uart1.read() == b'123456')

print(uart1.write(b'123') == 3)
print(uart0.read(1) == b'1')
print(uart0.read(2) == b'23')
print(uart0.read() == None)

uart0.write(b'123')
buf = bytearray(3)
print(uart1.readinto(buf, 1) == 1) 
print(buf)
print(uart1.readinto(buf) == 2)
print(buf)

# try initializing without the id