Esempio n. 1
20
def get_GPS_array():    
    com = UART(1,pins=(config.TX, config.RX),  baudrate=9600) 
    my_gps = MicropyGPS()
    time.sleep(2)
    if com.any():
        my_sentence = com.readline()
        for x in my_sentence:
            my_gps.update(chr(x)) 
        gps_array = convert_latlon(my_gps.latitude[0] + (my_gps.latitude[1] / 60), my_gps.longitude[0] + (my_gps.longitude[1] / 60))
        return gps_array
Esempio n. 2
1
def start_GPS():    
    com = UART(1,pins=("P11","P12"),  baudrate=9600) 
    my_gps = MicropyGPS()
    if config.LOG == 1:
        mount_sd()
        my_gps.start_logging('/sd/log.txt')
        my_gps.write_log('Restarted logging')

    while True:
        if com.any():
            my_sentence = com.readline()
            for x in my_sentence:
                my_gps.update(chr(x))
            print('Latitude: ' + my_gps.latitude_string() + ' Longitude: ' + my_gps.longitude_string() + ' Altitude: ' + str(my_gps.altitude))
            print('Lat / Lon: ' + str(my_gps.latitude[0] + (my_gps.latitude[1] / 60)) + ', ' + str(my_gps.longitude[0] + (my_gps.longitude[1] / 60)))
Esempio n. 3
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
Esempio n. 4
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
Esempio n. 5
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
Esempio n. 6
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()
Esempio n. 7
0
def sendRPi(toSend):  #function to transmit data to RPi

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

    toSend = str("{0:0=3d}".format(len(toSend) + 3)
                 ) + toSend  #adds in the beginning the length of the buffer

    while True:
        uart1.write(bytes(toSend, 'utf-8'))
        receivedMessage = ''
        timeOut = time.time() + 0.02
        while time.time(
        ) < timeOut:  #waits for 0.02 seconds for message back from RPi
            if (uart1.any()):
                receivedMessage = uart1.readall().decode('utf-8')

                if 'received' in receivedMessage:  #if receives 'received' breaks earlier
                    break

        if 'received' in receivedMessage:  #if is received,sends a new buffer
            print('\n***received!***')
            break
        else:  #sends the same buffer again
            print('\nsend again...')
Esempio n. 8
0
class WaterLevel:
    def __init__(self, port):
        self.port = port
        self.uart = UART(port, 9600)
        self.uart.init(9600,
                       timeout=10)  # 9600, 1byte about 1ms, wait for 10ms
        self.buffer = RingBuffer(10)

    # return
    # False: no change
    # True: change, need read value
    def Check(self):
        count = self.uart.any()
        if count < 3:
            return False
            # At lease 3 bytes in buffer (For example:0mm)

        value_change = None

        while 1:  # maybe too many data in UART RX buffer
            data = self.uart.readline()
            if data:
                number_string = re.search(b'^\d+', data)
                if number_string:
                    number = int(number_string.group(0))
                    value_change = self.buffer.InsertData(number, True)

            else:
                break

        return value_change

    def GetValue(self):
        return self.buffer.GetAverage()
Esempio n. 9
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)
Esempio 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)
Esempio n. 11
0
class Syringe_pump():
    def __init__(self, port):
        assert port.UART is not None, '! Pump needs port with UART.'
        self.uart = UART(port.UART, 9600)
        self.uart.init(9600, bits=8, parity=None, stop=1, timeout=100)
        self.uart.write('C')
        self.uart.write('Z')

    def infuse(self, val):
        self.uart.write('I,{}\n'.format(val))

    def check_for_serial(self):
        if self.uart.any():
            return self.uart.readline().decode("utf-8").strip('\n')
        else:
            return None

    def reset_volume(self):
        self.uart.write('Z')

    def retract(self):
        self.uart.write('R')

    def send_animal_number(self, number):
        self.uart.write('A,{}\n'.format(number))
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)
Esempio n. 13
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
Esempio n. 14
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
Esempio n. 15
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()
Esempio n. 16
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())
class SEN0219_SERIAL:

    # byte mhzCmdReadPPM[9] = {0xFF,0x01,0x86,0x00,0x00,0x00,0x00,0x00,0x79};
    # byte mhzResp[9];    // 9 bytes bytes response
    # byte mhzCmdCalibrateZero[9] = {0xFF,0x01,0x87,0x00,0x00,0x00,0x00,0x00,0x78};
    # byte mhzCmdABCEnable[9] = {0xFF,0x01,0x79,0xA0,0x00,0x00,0x00,0x00,0xE6};
    # byte mhzCmdABCDisable[9] = {0xFF,0x01,0x79,0x00,0x00,0x00,0x00,0x00,0x86};
    # byte mhzCmdReset[9] = {0xFF,0x01,0x8d,0x00,0x00,0x00,0x00,0x00,0x72};

    def __init__(self, TX, RX):
        self.uart = UART(1, 9600, bits=8, parity=None, stop=1, pins=(TX,RX))
        #self.uart.write(b'\xFF\x01\x8D\x00\x00\x00\x00\x00\x72') #Reset

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

    def SEN_Serial_ABCOn(self):
        self.uart.write(b'\xFF\x01\x79\xA0\x00\x00\x00\x00\xE6') #ABC On
        self.uart.wait_tx_done(1000)

    def SEN_Serial_ABCOff(self):
        self.uart.write(b'\xFF\x01\x79\x00\x00\x00\x00\x00\x86') #ABC Off
        self.uart.wait_tx_done(1000)

    def SEN_Serial_read(self):
        self.uart.write(b'\xFF\x01\x86\x00\x00\x00\x00\x00\x79') #get gas command
        self.uart.wait_tx_done(1000)
        Attempts=5
        while(Attempts>0):
            data=self._SerialRead()
            if(data!=False):
                return data
            Attempts-=1
            utime.sleep(1)
        return False

    def _SerialRead(self):
        print(str(self.uart.any()))
        if(self.uart.any()>=9):
            data=self.uart.read(9)
            return data
        else:
            return False
Esempio n. 18
0
def coms_test():
    crc_valid = None

    blue_wire_oe_n = Pin('P11', mode=Pin.OUT, pull=Pin.PULL_UP)
    blue_wire_oe_n.value(1)

    uart1 = UART(1, 25000)
    uart1.init(25000, bits=8, parity=None, stop=1)
    tx_buffer_flushed = None
    (data,crc_valid) = ctrl.data_frame(run_crc=True)
    print("Sending: {}\r".format(ubinascii.hexlify(data)),end='\n')
    start_time = time.ticks_us()
    blue_wire_oe_n.value(0)
    t_2_heater = time.ticks_diff(time.ticks_us(), start_time)
    print("t_2_heater {}us OE low".format(t_2_heater))
    start_time = time.ticks_us()
    uart1.write(data)
    tx_buffer_flushed = uart1.wait_tx_done(25)
    t_2_heater = time.ticks_diff(time.ticks_us(), start_time)
    print("t_2_heater {}us Tx".format(t_2_heater))
    start_time = time.ticks_us()
    blue_wire_oe_n.value(1)
    t_2_heater = time.ticks_diff(time.ticks_us(), start_time)
    print("t_2_heater {}us OE high buf flushed{}".format(t_2_heater,tx_buffer_flushed))
    start_time = time.ticks_us()
    num_bytes = uart1.any()
    
    while (num_bytes < 24) :
       num_bytes = uart1.any() 
    t_2_heater = time.ticks_diff(time.ticks_us(), start_time)
    print("t_2_heater {}us to get heater data".format(t_2_heater))
    start_time = time.ticks_us()
    data = util.extractValidFrameFromUART(uart1)
    t_2_heater = time.ticks_diff(time.ticks_us(), start_time)
    print("t_2_heater {}us to extract and load".format(t_2_heater))
    
    print("Halting")
    machine.idle()  
    
    while True:
        pass
Esempio n. 19
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)
Esempio n. 20
0
File: gps.py Progetto: 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)
Esempio n. 21
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
Esempio n. 22
0
class GPS_data():
    def __init__(self):
        self.uart = UART(1, pins=(config.TX, config.RX), baudrate=9600)
        self.gps_dev = MicropyGPS()

    def get_loc(self):
        coords = array.array('B', [0, 0, 0, 0, 0, 0, 0, 0, 0])
        timestamp = (0, 0, 0)
        valid = False
        sentence = ''
        # read buffer to last line
        while self.uart.any():
            sentence = self.uart.readline()
        # if timed-out process last line
        if len(sentence) > 0:
            for x in sentence:
                self.gps_dev.update(chr(x))
            if config.DEBUG:
                print(sentence)
                print('Longitude', self.gps_dev.longitude)
                print('Latitude', self.gps_dev.latitude)
                print('UTC Timestamp:', self.gps_dev.timestamp)
                print('Fix Status:', self.gps_dev.fix_stat)
                print('Altitude:', self.gps_dev.altitude)
                print('Horizontal Dilution of Precision:', self.gps_dev.hdop)
                print('Satellites in Use by Receiver:',
                      self.gps_dev.satellites_in_use)
            if self.has_fix():
                valid = True
                timestamp = self.gps_dev.timestamp
                lat = int((self.gps_dev.latitude[0] +
                           (self.gps_dev.latitude[1] / 60) + 90) * 10000)
                lon = int((self.gps_dev.longitude[0] +
                           (self.gps_dev.longitude[1] / 60) + 180) * 10000)
                alt = int((self.gps_dev.altitude) * 10)
                lhdop = int((self.gps_dev.hdop) * 10)
                # encode location data
                coords[0] = lat
                coords[1] = (lat >> 8)
                coords[2] = (lat >> 16)
                coords[3] = lon
                coords[4] = (lon >> 8)
                coords[5] = (lon >> 16)
                coords[6] = alt
                coords[7] = (alt >> 8)
                coords[8] = lhdop
        return coords, timestamp, valid

    def has_fix(self):
        return (self.gps_dev.fix_stat > 0 and self.gps_dev.latitude[0] > 0)
Esempio n. 23
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")
Esempio n. 24
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')
Esempio n. 25
0
def do():
    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)
    uart.write('J000000')
    utime.sleep_ms(1000)
    uart.write('\r\n')
    utime.sleep_ms(500)
    uart.write('\r\n')
    utime.sleep_ms(100)
    uart.write('Y\r\n')
    utime.sleep_ms(100)
    while uart.any():
        print(uart.readline())
    utime.sleep_ms(50)
    uart.write('10 PRINT "HI"\r\n')
    utime.sleep_ms(50)
    uart.write('20 FOR F=1 TO 10\r\n')
    utime.sleep_ms(50)
    uart.write('30 PRINT F\r\n')
    utime.sleep_ms(50)
    uart.write('40 NEXT F\r\n')
    utime.sleep_ms(50)
    uart.write('RUN\r\n')
    utime.sleep_ms(200)
    while uart.any():
        print(uart.readline())
    while True:
        while uart.any():
            print(uart.readline())
        utime.sleep_ms(100)
Esempio n. 26
0
def config_M8():
    u = UART(1, 9600)
    u.init(9600, bits=8, parity=None, stop=1)
    # UBX-CFG-PRT command to set UART1 output=0 (UBX output only) and 9600 baud
    buf1 = b'\xB5\x62\x06\x00\x14\x00\x01\x00\x00\x00\xC0\x08\x00\x00\x80\x25\x00\x00\x07\x00\x01\x00\x00\x00\x00\x00\x90\xA9'
    u.write(buf1)
    # catch ack
    while not u.any():
        if u.any():
            break
    poll = u.read()
    # write UBX-CFG-PRT poll command
    buf1 = b'\xB5\x62\x06\x00\x01\x00\x01\x08\x22'
    u.write(buf1)
    # catch poll response
    while not u.any():
        if u.any():
            break
    poll = u.read()
    u.deinit()  # this closes the UART
    REGISTER_FORMAT = '<i'  # little endian 4 bytes
    # offset for baud rate = 6 + 8
    baud = ustruct.unpack_from(REGISTER_FORMAT, poll, 14)[0]
    print('baud rate= ', baud)
Esempio n. 27
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)
Esempio n. 28
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)
Esempio n. 29
0
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()
Esempio n. 30
0
def UartRead():
    global state
    uart = UART(UART.UART1, 115200, 8, 0, 1, 0)
    while 1:
        # 返回是否有可读取的数据长度
        msgLen = uart.any()
        # 当有数据时进行读取
        if msgLen:
            msg = uart.read(msgLen)
            # 初始数据是字节类型(bytes),将字节类型数据进行编码
            utf8_msg = msg.decode()
            # str
            uart_log.info("UartRead msg: {}".format(utf8_msg))
        else:
            continue
    state = 0
Esempio n. 31
0
        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

time.sleep_us(100)
Esempio n. 32
0
# 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)

# register my task
blynk.set_user_task(sendData, 60000)
Esempio n. 33
0
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])
uart0.write(b'1234567890')
time.sleep_ms(2) # because of the fifo interrupt levels
print(uart1.any() == 10)
print(uart1.readline() == b'1234567890')
print(uart1.any() == 0)

uart0.write(b'1234567890')
print(uart1.readall() == b'1234567890')

# tx only mode
uart0 = UART(0, 1000000, pins=('GP12', None))
print(uart0.write(b'123456') == 6)
print(uart1.read() == b'123456')
print(uart1.write(b'123') == 3)
print(uart0.read() == None)

# rx only mode
uart0 = UART(0, 1000000, pins=(None, 'GP13'))