Ejemplo n.º 1
0
class uart_class(object):
    def __init__(self, port, baudrate=115200, timeout=2, timeout_char=1):
        self.port = PORT[port]
        self.uart = UART(self.port, baudrate, timeout, timeout_char)

    @decorator
    def write(self, data):
        self.uart.write(data)

    @decorator
    def read(self):
        _bytes = self.uart.read(MAX_RECEIVE_SIZE)
        return _bytes

    #@decorator
    def is_received(self, _str):
        _bytes = self.uart.read(MAX_RECEIVE_SIZE)
        #print(_bytes)
        received_str = str(_bytes, "utf-8")
        if (received_str == _str):
            return True
        else:
            return False

    @decorator
    def get_string(self):
        _bytes = self.uart.read(MAX_RECEIVE_SIZE)
        #print(_bytes)
        return str(_bytes, "utf-8")

    @decorator
    def any(self):
        return self.uart.any()
Ejemplo n.º 2
0
class XLMaxSonarUART:
    def __init__(self, channel=2, rx=12, tx=13):
        self.DEVICE_TYPE = 'XL-MAXSONAR'
        self._uart = UART(channel, baudrate=9600, bits=8, parity=None, stop=1, rx=rx, tx=tx,
                          invert=UART.INV_RX | UART.INV_TX, timeout=100, timeout_char=100)

    @property
    def range(self):
        self.start()
        sleep(0.1)
        return self.read()

    def start(self):
        self._uart.write(b'\x01')  # create pulse on TX pin

    def read(self):
        i = 0
        data = b''
        while i < _IO_TIMEOUT:
            data = self._uart.read(1)
            if data == b'R':
                data = self._uart.read(4)[:3]
                return int(data.decode())
            elif data is None:
                self.start()
            i += 1
Ejemplo n.º 3
0
class SDS011:
    def __init__(self, uart=1, rxpin='P11'):
        self.uart = uart
        self.rxpin = rxpin
        self._hasValues = False
        self._uart = UART(uart, pins=(None, rxpin))

    @property
    def has_values(self):
        return self._hasValues

    def values(self):
        b = self._uart.readall()  #Empty the uart buffer
        while True:
            while self._uart.read(1) != b'\xaa':  # Wait for packet start
                pass
            if self._uart.read(1) != b'\xc0':  # Should be C0
                continue
            b = self._uart.read(7)  # Data + checksum
            if self._uart.read(1) != b'\xab':  # Tail
                continue
            s = struct.unpack('BBBBBBB', b)  # Check the checksum
            sum = s[0] + s[1] + s[2] + s[3] + s[4] + s[5]
            if sum % 256 != s[6]:
                continue
            return struct.unpack('<HHBB', b)  # (PM2.5x10, PM10x10, ID1, ID2)
Ejemplo n.º 4
0
class airspeed:
    # --------------------------------------------------------------------------
    # Initialisation method
    # --------------------------------------------------------------------------
    def __init__(self, bmp, baud=115200, tx=17, rx=16):
        self.bmp = bmp
        self.uart = UART(1,baud,tx=tx,rx=rx)
        #self.std_p = 101655
        # Calculate pressure offset
        while(True):
            reading = self.uart.read()
            if reading == None:
                continue
            else:
                pressure = self.readPressure(reading)
                break
        self.offset_p = self.bmp.pressure - pressure
        self.density = 1.225

    # --------------------------------------------------------------------------
    # Read the airspeed from the airspeed sensor
    # --------------------------------------------------------------------------
    def read(self):
        reading = self.uart.read()
        if(reading == None):
            return None
        pressure = self.readPressure(reading)
        temp = self.readTemp(reading)
        speed = math.sqrt(abs( (2*(pressure - self.bmp.pressure + self.offset_p)) / self.density) )

        return speed
    
    def readPressure(self, reading):
        return reading[4] \
            + (reading[5] << 8) \
            + (reading[6] << 16) \
            + (reading[7] << 24)

    def readTemp(self, reading):
        return reading[8] \
            + (reading[9] << 8) \
            + (reading[10] << 16) \
            + (reading[11] << 24)
    

# 102087.3 kPa

#prev_time = utime.ticks_us()

#def pin_handle(pin):
#    global prev_time
#    print(utime.ticks_diff(utime.ticks_us(), prev_time))
#    prev_time = utime.ticks_us()

#p17 = Pin(17, Pin.OUT)
#p17.off()

#p16 = Pin(16, Pin.IN)
#p16.irq(pin_handle)
Ejemplo n.º 5
0
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
Ejemplo n.º 6
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
Ejemplo n.º 7
0
class CORGI85():
    def __init__(self):
        try:
            fm.register(board_info.WIFI_RX, fm.fpioa.UART2_TX)
            fm.register(board_info.WIFI_TX, fm.fpioa.UART2_RX)
            self.uart = UART(UART.UART2,
                             115200,
                             8,
                             None,
                             1,
                             timeout=1000,
                             read_buf_len=4096)
            print("Init CORGI85")
        except:
            print("Unable to init UART")

    def deinit(self):
        self.uart.deinit()
        del self.uart

    def wifi_check(self):
        data = self.uart.read()
        self.uart.write("\rWIFI_CHECK,\r")
        time.sleep_ms(100)
        if self.uart.any() > 0:
            data = self.uart.read()
            return int(data[0])
        else:
            return 0

    def thingspeak_init(self):
        print(">>> thingspeak_init")
        self.uart.write("\rThingspeak,init\r")

    def thingspeak_account_setup(self, api_key, channel_id):
        print(">>> thingspeak_account_setup")
        self.uart.write("\rThingspeak,account_setup,")
        self.uart.write(str(api_key))
        self.uart.write(",")
        self.uart.write(str(channel_id))
        self.uart.write("\r")

    def thingspeak_write_field(self, field, value):
        print(">>> thingspeak_write_field, field : ", field, ", value : ",
              value)
        self.uart.write("\rThingspeak,write_field,")
        self.uart.write(str(field))
        self.uart.write(",")
        self.uart.write(str(value))
        self.uart.write("\r")
    def gps_device(self):

        try:
            gps_tx = self.cfg('pins_devices')['gps_uart_rx']
            gps_rx = self.cfg('pins_devices')['gps_uart_rx']

            uart_gps = UART(2, 115200, tx=gps_tx, rx=gps_rx)
            uart_gps.init(9600,
                          bits=8,
                          parity=None,
                          stop=1,
                          tx=gps_tx,
                          rx=gps_rx)

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

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

                recv = uart_gps.read(-1)
                if (recv == None):
                    continue
                if (recv.find(b'\n') >= 0):
                    print("[device] gps-response \t\t\t[OK]")
                    return uart_gps
                else:
                    continue

        except:
            print("[gps] response \t\t\t\t[FAILED]")
            return None
Ejemplo n.º 9
0
def fetch_standard_data():
    device = UART(UART_ID,
                  baudrate=300,
                  bits=7,
                  parity=0,
                  stop=2,
                  timeout=3000)
    device.write("/#1".encode("utf-8"))
    sleep(1)

    # Kamstrup Multical 66C docs specify stopbits = 2, however on ESP8266 this results into gibberish
    device.init(baudrate=1200, bits=7, parity=0, stop=1, timeout=3000)
    response = device.read(87)

    # whitespaces are discarded in some readings
    # nevertheless, ASCII numbers are always complete,
    # so we split it manually
    data = response.decode("utf-8").replace(" ", "")
    parts = [data[i:i + 7] for i in range(0, len(data), 7)]
    return {
        "energy": int(parts[0]) / 100,
        "volume": int(parts[1]) / 100,
        "temperature_flow": int(parts[3]) / 100,
        "temperature_return": int(parts[4]) / 100
    }
Ejemplo n.º 10
0
def run():
    """Run the program."""
    uart = UART(1)
    uart.init(config.baudrate,
              bits=8,
              parity=None,
              stop=1,
              rx=config.rx,
              tx=config.tx)
    gps = MicropyGPS()
    s = screen.Screen()

    kph = None
    start = utime.ticks_ms()
    while kph is None and utime.ticks_diff(utime.ticks_ms(), start) < 1000:
        if uart.any():
            try:
                stat = gps.update(chr(uart.read(1)[0]))
            except:
                pass
            if stat == 'GNRMC':
                print(stat)
                kph = gps.speed[2]

    if kph is not None:
        s.update(kph)

    machine.deepsleep(5000)
Ejemplo n.º 11
0
class IR:
    def __init__(self, rx, tx):
        self.uart = UART(1, baudrate=115200, rx=rx, tx=tx, timeout=10)
        self._write_flag = 0
        self.ac_state = 0

    def uartSend(self, t):
        self.uart.write(t)

    def write(self, name, str):
        f = open(name, "wb")
        f.write(str)
        f.close()

    def read(self, name):
        f = open(name, "rb")
        data = f.read()
        f.close()
        return data

    def main(self):
        time.sleep_ms(100)
        if self.uart.any():
            a = self.uart.read()
            if a != b'\xfe\xfc\xcf':
                if self._write_flag:
                    file_name = "ir_Data/Ac_" + self._write_flag
                    self.write(file_name, a)
            return a
Ejemplo n.º 12
0
class TJC3224T024(object):
    def __init__(self, uart=None):
        if uart is None:
            self.uart = UART(1, 9600)  # UART on
            self.uart.init(9600, bits=8, parity=None, stop=1)
        else:
            self.uart = uart

    def send_text(self, tn, text):
        txt = '{0}.txt="{1}"'.format(tn, text)
        self.exec_cmd(txt)

    def send_line(self, tn, text):
        txt = '{0}.txt=t0.txt+"{1}"'.format(tn, text)
        self.exec_cmd(txt)

    def send_enter(self, tn):
        txt = '{0}.txt={1}.txt+"\\r"'.format(tn, tn)
        self.exec_cmd(txt)

    def cls(self, tn):
        txt = '{0}.txt=""'.format(tn)
        self.exec_cmd(txt)

    def exec_cmd(self, txt):
        self.uart.write(txt)
        self.uart.write(b'\xff\xff\xff')
        self.read_all()

    def read_all(self):
        data = self.uart.read()
        print(data)
Ejemplo n.º 13
0
class Bluetooth_car():
    def __init__(self):
        self.uart = UART(2,
                         baudrate=9600,
                         rx=pin9.pin,
                         tx=pin8.pin,
                         timeout=10)
        self.uart.init(parity=None, stop=1, bits=8)
        self.msg = ""

    def check_bluetooth(self):
        a = self.uart.read()
        if a != None:
            #str(a, "utf-8").strip("\n")
            self.msg = a  #str(a, "utf-8") #.strip("\n")
            return True
        else:
            return False

    def msg_ble(self, dabble=True):
        if dabble:
            return keycodes.get(
                binascii.hexlify(self.msg).decode(), "not support")
        else:
            return self.msg
Ejemplo n.º 14
0
def main():
    """
    config uart Baud rate as 115200,data bits as 8bit, Do not use parity,
    Stop bit as 0bit,Do not use Flow control,
    UART(UART.UARTn, buadrate, databits, parity, stopbits, flowctl)
    """
    uart = UART(UART.UART2, 115200, 8, 0, 1, 0)
    # write string
    delay = 100
    for i in range(2):
        # write string
        uart.write("hello world\r\n")
        # write string and & integer
        uart.write("delay num as {0}ms\r\n".format(delay))
        # write float
        uart.write("π as {0}\r\n".format(3.14159))
        # read something
        read_btyes = 6
        uart.write("please input {0} bytes:\r\n".format(read_btyes))
        while True:
            if uart.any() > read_btyes:
                break
            else:
                time.sleep_ms(10)
        # !!! Before reading buffer, please make sure there is data in buffer
        input_date = uart.read(read_btyes)
        uart.write("The data you entered is {0}\r\n".format(input_date))
        time.sleep_ms(delay)
Ejemplo n.º 15
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))
Ejemplo n.º 16
0
class ESP01S():
    def __init__(self, uart_port=0, txPin=16, rxPin=17):
        self.uart = UART(0, baudrate=115200, tx=Pin(txPin), rx=Pin(rxPin))
        self.echo(False)

    def echo(self, enable=False):
        if enable:
            self.send("ATE1")
        else:
            self.send("ATE0")

    def send(self, cmd):
        self.uart.write(cmd + "\r\n")

        rxData = ""
        while True:
            if self.uart.any() > 0:
                break
        while self.uart.any() > 0:
            rxData += str(self.uart.read(1))
        rxData = rxData.replace("b'", "")
        rxData = rxData.replace("\\r", "")
        rxData = rxData.replace("\\n", "\n")
        rxData = rxData.replace("'", "")
        return rxData
Ejemplo n.º 17
0
class Terminal:
    def __init__(self, pybytes_protocol):
        self.__pybytes_protocol = pybytes_protocol
        self.original_terminal = UART(0, 115200)
        self.message_from_pybytes = False
        self.message_to_send = ''

    def write(self, data):
        if self.message_from_pybytes:
            self.message_to_send += data
            # self.__pybytes_protocol.__send_terminal_message(data)
        else:
            self.original_terminal.write(data)

    def read(self, size):
        return self.original_terminal.read(size)

    def message_sent_from_pybytes_start(self):
        self.message_from_pybytes = True

    def message_sent_from_pybytes_end(self):
        if self.message_to_send != '':
            self.__pybytes_protocol.__send_terminal_message(
                self.message_to_send)
            self.message_to_send = ''
        self.message_from_pybytes = False
Ejemplo n.º 18
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]
Ejemplo n.º 19
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()
Ejemplo n.º 20
0
class UartComm():
    """
    The main class for communication between the main input
    module and the WiFi module
    """
    def __init__(self):
        self.handlers = {}
        self._uart = UART(0, 115200)
        self._uart.init(115200, bits=8, parity=None, stop=1)

    def begin(self):
        """
        Enables the serial port to receive data, otherwise
        repl will not allow data being read 
        """
        uos.dupterm(None, 1)

    def end(self):
        """
        Re-enable the serial port to be used by REPL
        """
        uos.dupterm(UART(0, 115200), 1)

    def add_handler(self, command, callback):
        self.handlers[command] = callback

    def apply_command(self, display, command, *args):
        if command in self.handlers:
            self.handlers[command](*args)

    def _extract_input_instruction(self, display, data):
        """
        Extracts the command if found and applies it
        """
        command = data[0]
        self.apply_command(display, command, data[1:])

    def check_input(self, display):
        """
        This method is to be called whenever any serial
        data is available, it will try to extract commands
        """
        if not self._uart.any():
            return False
        
        uartdata = self._uart.read()
        #display.lcd.fill(0)
        #display.lcd.text(uartdata[3:], 0, 0, 1)
        #display.lcd.show()
        r = len(uartdata)
        while True:
            position = uartdata.rfind(INSTRUCTION, 0, r)
            if position < 0:
                break
            self._extract_input_instruction(display, uartdata[position+2:r])
            r = position
Ejemplo n.º 21
0
def run(hostname, client_id, mqtt_host, mqtt_port, mqtt_user, mqtt_pass, pin_enable, ssl = False):

    print('Disabling REPL on UART')
    uos.dupterm(None, 1)

    en1 = Pin(pin_enable, Pin.OUT, value=1)
    rx = UART(0, 115200, rxbuf = 1024)

    def on_msg(topic, msg):
        print(topic, msg)
        if topic == b"smarty_control":
            if msg == b"reset":
                machine.reset()

    mqtt_client_id = client_id + b"_smarty"

    c = MQTTClient(mqtt_client_id, mqtt_host, mqtt_port, mqtt_user, mqtt_pass,
        keepalive = 60,
        ssl = ssl)
    c.lw_topic = b"smarty_control"
    c.lw_msg = b"logoff/" + mqtt_client_id + b"/lastwill"
    c.set_callback(on_msg)
    c.connect()
    utime.sleep_ms(1000)
    c.publish(b"smarty_control", b"logon/" + mqtt_client_id)
    # c.subscribe(b"smarty_control")

    poll = uselect.poll()
    poll.register(rx, uselect.POLLIN)

    print('Requesting data')
    en1.value(0)

    while True:
        # c.check_msg()
        evs = poll.poll(10000)

        for ev in evs:
            if ev[0] == rx:
                if ev[1] == uselect.POLLERR:
                    print('error')
                elif ev[1] == uselect.POLLIN:
                    print('data ready')
                    data = b""
                    while rx.any() > 0:
                        data = data + rx.read()
                        utime.sleep_ms(5)
                    c.publish(b"smarty_data", data)
                    print(str(len(data)) + ' bytes sent')


    print('disabling')
    en1.value(1)

    c.publish(b"smarty_control", b"logoff/" + mqtt_client_id)
    c.disconnect()
Ejemplo n.º 22
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())
Ejemplo n.º 23
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)
Ejemplo n.º 24
0
def chk_GNSS():
    while True:
        u = UART(1, 9600)
        u.init(9600, bits=8, parity=None, stop=1)
        # UBX-NAV-STATUS hex poll command to check if position fix
        buf = b'\xB5\x62\x01\x03\x00\x00\x04\x0D'
        REGISTER_FORMAT = '>b'  # one byte for nav status
        u.write(buf)
        #sleep(1)
        while not u.any():
            if u.any():
                break
# read 24 bytes
        poll = u.read(24)
        # offset for nav fix byte = 6 + 5
        nav_fix = ustruct.unpack_from(REGISTER_FORMAT, poll, 11)[0]
        print('nav fix= ', (nav_fix & 0x01))
        # offset for nav status code byte = 6 + 4
        nav_stat = ustruct.unpack_from(REGISTER_FORMAT, poll, 10)[0]
        print('nav status code= ', nav_stat)
        # UBX-NAV-POSLLH hex poll command
        buf = b'\xB5\x62\x01\x02\x00\x00\x03\x0A'
        # send poll command
        u.write(buf)
        while not u.any():
            if u.any():
                break
# read UBX-NAV-POSLLH poll result
        poll = u.read(36)
        u.deinit()  # this closes the UART
        #print ('read nav data ',poll)
        REGISTER_FORMAT = '<i'  # little endian 4 bytes
        # offset for longitude status byte = 6 + 4
        lon = ustruct.unpack_from(REGISTER_FORMAT, poll, 10)[0]
        lat = ustruct.unpack_from(REGISTER_FORMAT, poll, 14)[0]
        if (nav_fix & 0x01) != 1:
            print('no GNSS signal', (nav_fix / 2))
        else:
            print('longitude= ', (lon / 1E7))
            print('latitude= ', (lat / 1E7))
        sleep(2)
Ejemplo n.º 25
0
def readsensor():

    uart = UART(1)
    uart.init(9600,
              bits=8,
              parity=None,
              stop=1,
              timeout_chars=100,
              pins=('P3', 'P4'))

    header_bytes = uart.read(1)
    while (header_bytes != b'\xff'):
        header_bytes = uart.read(1)
    HIGH = int(uart.read(1)[0])
    LOW = int(uart.read(1)[0])
    SUM = int(uart.read(1)[0])

    if (HIGH + LOW - SUM):
        distance = (HIGH * 256) + LOW
        print("Distance is: ", distance, "mm")
        return (distance)
        time.sleep(2)
Ejemplo n.º 26
0
def wifi_reset():
    global uart
    wifi_enable(0)
    time.sleep_ms(200)
    wifi_enable(1)
    time.sleep(2)
    uart = UART(UART.UART2,115200,timeout=1000, read_buf_len=4096)
    tmp = uart.read()
    uart.write("AT+UART_CUR=921600,8,1,0,0\r\n")
    print(uart.read())
    uart = UART(UART.UART2,921600,timeout=1000, read_buf_len=10240) # important! baudrate too low or read_buf_len too small will loose data
    uart.write("AT\r\n")
    tmp = uart.read()
    print(tmp)
    if not tmp.endswith("OK\r\n"):
        print("reset fail")
        return None
    try:
        nic = network.ESP8285(uart)
    except Exception:
        return None
    return nic
Ejemplo n.º 27
0
Archivo: gps.py Proyecto: KevMca/Apus
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)
Ejemplo n.º 28
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
Ejemplo n.º 29
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')
Ejemplo n.º 30
0
def wifi_init():
    global uart
    wifi_enable(0)
    time.sleep_ms(200)
    wifi_enable(1)
    time.sleep(2)
    uart = UART(UART.UART2, 115200, timeout=1000, read_buf_len=4096)
    tmp = uart.read()
    uart.write("AT+UART_CUR=921600,8,1,0,0\r\n")
    print(uart.read())
    uart = UART(UART.UART2, 921600, timeout=1000,
                read_buf_len=10240)  #实测模块波特率太低或者缓存长度太短会导致数据丢失。
    uart.write("AT\r\n")
    tmp = uart.read()
    print(tmp)
    if not tmp.endswith("OK\r\n"):
        print("reset fail")
        return None
    try:
        nic = network.ESP8285(uart)
    except Exception:
        return None
    return nic
Ejemplo n.º 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)
Ejemplo n.º 32
0

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

time.sleep_us(100)
print(uart0.any() == 5)
print(uart0_int_count > 0)
print(uart0_irq.flags() == 0)
print(uart1_irq.flags() == 0)
print(uart0.read() == b"12345")

# do it again
uart1_int_count = 0
Ejemplo n.º 33
0
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
uart0 = UART(baudrate=1000000, pins=uart_pins[0][0])
Ejemplo n.º 34
0
import utime
from machine import I2C, Pin, UART, unique_id
import neopixel, machine


id = unique_id()
chipId='{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}'.format(id[0], id[1], id[2], id[3], id[4], id[5])
print('chipId shows: ', chipId)
i2c = machine.I2C(scl=Pin(22), sda=Pin(21))
print('i2c bus shows: ', i2c.scan())
uart2=UART(1,rx=26,tx=27,baudrate=9600)
uart1=UART(2,rx=0,tx=2,baudrate=9600)
utime.sleep(2)
print('uart1 shows:', uart1.read(32))
print('uart2 shows:', uart2.read(32))
RED = (255,0,0); GREEN = (0,255,0); BLUE = (0,0,255)
colors = [RED, GREEN, BLUE]
np = neopixel.NeoPixel(Pin(12), 1)
for color in colors:
	np[0] = color
	np.write()
	utime.sleep(1)