def during_bootup(self, keyboard): # Set up name for target side detection and BLE advertisment name = str(getmount('/').label) if self.split_type == SplitType.BLE: self._ble.name = name else: # Try to guess data pins if not supplied if not self.data_pin: self.data_pin = keyboard.data_pin # Detect split side from name if self.split_side is None: if name.endswith('L'): # If name ends in 'L' assume left and strip from name self._is_target = bool(self.split_target_left) self.split_side = SplitSide.LEFT elif name.endswith('R'): # If name ends in 'R' assume right and strip from name self._is_target = not bool(self.split_target_left) self.split_side = SplitSide.RIGHT # if split side was given, find master from split_side. elif self.split_side == SplitSide.LEFT: self._is_target = bool(self.split_target_left) elif self.split_side == SplitSide.RIGHT: self._is_target = not bool(self.split_target_left) # Flips the col pins if PCB is the same but flipped on right if self.split_flip and self.split_side == SplitSide.RIGHT: keyboard.col_pins = list(reversed(keyboard.col_pins)) self.split_offset = len(keyboard.col_pins) if self.split_type == SplitType.UART and self.data_pin is not None: if self._is_target: self._uart = busio.UART( tx=self.data_pin2, rx=self.data_pin, timeout=self._uart_interval ) else: self._uart = busio.UART( tx=self.data_pin, rx=self.data_pin2, timeout=self._uart_interval ) # Attempt to sanely guess a coord_mapping if one is not provided. if not keyboard.coord_mapping: keyboard.coord_mapping = [] rows_to_calc = len(keyboard.row_pins) * 2 cols_to_calc = len(keyboard.col_pins) * 2 for ridx in range(rows_to_calc): for cidx in range(cols_to_calc): keyboard.coord_mapping.append(intify_coordinate(ridx, cidx))
def tr_init(): tr_power_levels = {"command":0x46,"payload":powers} tr_frequencies = {"command":0x50,"payload":band} tr_unlock = {"command":None,"payload":None} tr_get_settings = {"command":0x76,"payload":None} tr_uart = busio.UART(board.TX, board.RX, baudrate=9600,bits=8,parity=None,stop=None,timeout=1,receiver_buffer_size=64) return tr_power_levels,tr_frequencies,tr_unlock,tr_get_settings,tr_uart
def is_hardware_uart(tx, rx): try: p = busio.UART(tx, rx) p.deinit() return True except ValueError: return False
def setup(): VirtualWire.vw_tx_pin(12) busio.UART(board.TX, board.RX, baudrate=9600) print("setup") VirtualWire.vw_set_ptt_inverted.Value = True VirtualWireA.setup_vw.Value = True return
def __init__(self, update_period=1000, baudrate=9600): """ :param int update_period: (Optional) The amount of time in milliseconds between updates (default=1000) :param int baudrate: (Optional) The Serial Connection speed to the GPS (default=9600) """ if not isinstance(update_period, int): raise ValueError( "Update Frequency should be an integer in milliseconds") if update_period < 250: raise ValueError("Update Frequency be at least 250 milliseconds") timeout = update_period // 1000 + 2 if timeout < 3: timeout = 3 self._uart = busio.UART(board.TX, board.RX, baudrate=baudrate, timeout=timeout) self._gps = adafruit_gps.GPS(self._uart, debug=False) # Turn on the basic GGA and RMC info self._gps.send_command( bytes('PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0', 'utf-8')) self._gps.send_command( bytes('PMTK220,{}'.format(update_period), 'utf-8'))
def get_uart(): global _uart if not _uart: _uart = busio.UART(rx=board.ESP_RTS, tx=board.ESP_CTS, \ rts=board.ESP_HOST_WK, cts=board.ESP_BOOT_MODE, \ baudrate=1_000_000, timeout=30, receiver_buffer_size=2500) return _uart
def __init__(self, tx_pin, rx_pin, brc_pin, baud_rate=115200, trace=False): """ Initialize communication pins and state. State is referred to as operating mode to stay consistent with the Open Interface Specification document. Two list are created to capture operating mode and command history. Both store the last 5 items processed. If trace is enabled the last 10 commands will be captured in self.history. History tuple structure: (operating_mode, command, data_bytes) """ self._board = busio.UART(tx_pin, rx_pin, baudrate=baud_rate) self._tx_pin = tx_pin self._rx_pin = rx_pin self._brc_pin = brc_pin self._baud_rate = baud_rate self._operating_mode = "off" self.trace = trace # Could be expensive for an embedded environment. if trace: self._history = [None for i in range(10)] self._brc_pin.direction = digitalio.Direction.OUTPUT
def __init__(self, debug=False): uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=3000) super(Gps, self).__init__(uart, debug=debug) self._fields = list() self._fields.extend(Gps._KEYS[0:3]) Gps._DIS_PIN.direction = digitalio.Direction.OUTPUT Gps._DIS_PIN.value = False
def __init__(self): """ Big init routine as the whole board is brought up. """ self.hardware = { 'SDcard': False, 'ESP32': False, 'Neopixel': False, } self.payload = None self.filename = '' # Define LEDs: self._led = digitalio.DigitalInOut(board.LED) self._led.switch_to_output() # Define battery voltage # self._vbatt = analogio.AnalogIn(board.BATTERY) # Define SPI,I2C,UART self._spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) self._uart = busio.UART(board.TX2, board.RX2) # Define sdcard self._sdcs = digitalio.DigitalInOut(board.xSDCS) self._sdcs.direction = digitalio.Direction.OUTPUT self._sdcs.value = True # Initialize sdcard try: import adafruit_sdcard self._sd = adafruit_sdcard.SDCard(self._spi, self._sdcs) self._vfs = storage.VfsFat(self._sd) storage.mount(self._vfs, "/sd") sys.path.append("/sd") self.hardware['SDcard'] = True except Exception as e: print('[WARNING]', e) # Define ESP32 self._esp_dtr = digitalio.DigitalInOut(board.DTR) self._esp_rts = digitalio.DigitalInOut(board.RTS) self._esp_cs = digitalio.DigitalInOut(board.TMS) #GPIO14 self._esp_rdy = digitalio.DigitalInOut(board.TCK) #GPIO13 self._esp_cs.direction = digitalio.Direction.OUTPUT self._esp_dtr.direction = digitalio.Direction.OUTPUT self._esp_rts.direction = digitalio.Direction.OUTPUT self._esp_cs.value = True self._esp_dtr.value = False self._esp_rts.value = False # Initialize Neopixel try: self.neopixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2, pixel_order=neopixel.GRB) self.neopixel[0] = (0, 0, 0) self.hardware['Neopixel'] = True except Exception as e: print('[WARNING]', e)
def __init__( self, secrets_, *, esp01_pins=[], esp01_uart=None, esp01_baud=115200, pub_prefix="", debug=False ### pylint: disable=redefined-outer-name ): if esp01_uart: self.esp01_uart = esp01_uart else: self.esp01_uart = busio.UART(*esp01_pins, receiver_buffer_size=2048) self.debug = debug self.esp = adafruit_espatcontrol.ESP_ATcontrol(self.esp01_uart, esp01_baud, debug=debug) self.esp_version = "" self.wifi = None try: _ = [secrets_[key] for key in self.SECRETS_REQUIRED] except KeyError: raise RuntimeError("secrets.py must contain: " + " ".join(self.SECRETS_REQUIRED)) self.secrets = secrets_ self.io = None self.pub_prefix = pub_prefix self.pub_name = {} self.init_connect()
def __init__(self, tx_pin, rx_pin, brc_pin, baud_rate=115200): self._board = busio.UART(tx_pin, rx_pin, baudrate=baud_rate) self._tx_pin = tx_pin self._rx_pin = rx_pin self._brc_pin = brc_pin self._brc_pin.direction = digitalio.Direction.OUTPUT self._baud_rate = baud_rate
def __init__(self): isDeployed = getDeployStatus() if !isDeployed: deploy() self.currentState = "start" sd = testSD.SD() uart = busio.UART(board.TX, board.RX, baudrate=9600)
def main(): # Initialize print("opening port") try: if sys.implementation.name == 'circuitpython': if use_uart: # https://circuitpython.readthedocs.io/en/2.x/shared-bindings/busio/UART.html port = busio.UART(board.TX, board.RX, baudrate=9600) else: # https://circuitpython.readthedocs.io/en/2.x/shared-bindings/busio/I2C.html port = busio.I2C(board.SCL, board.SDA) elif sys.implementation.name == 'micropython': if use_uart: # https://docs.micropython.org/en/latest/library/machine.UART.html # ESP32 IO2 RX:16 TX:17 port = UART(2, 9600) port.init(9600, bits=8, parity=None, stop=1) else: # https://docs.micropython.org/en/latest/library/machine.I2C.html port = I2C() elif sys.implementation.name == 'cpython': if use_uart: # https://github.com/vsergeev/python-periphery#serial if sys.platform == "linux" or sys.platform == "linux2": if use_periphery: port = Serial("/dev/serial0", 9600) else: port = serial.Serial(port="/dev/serial0", baudrate=9600) elif sys.platform == "darwin": port = serial.Serial(port="/dev/tty.usbmodemNOTE1", baudrate=9600) elif sys.platform == "win32": port = serial.Serial(port="COM21", baudrate=9600) else: # https://github.com/vsergeev/python-periphery#i2c if use_periphery: port = I2C("/dev/i2c-1") else: raise Exception("I2C not supported on platform: " + sys.platform) except Exception as exception: raise Exception("error opening port: " + ExceptionInfo(exception)) print("opening notecard") try: if use_uart: card = notecard.OpenSerial(port) else: card = notecard.OpenI2C(port, 0, 0) except Exception as exception: raise Exception("error opening notecard: " + ExceptionInfo(exception)) # If success, do a transaction loop print("transaction loop") while True: time.sleep(2) transactionTest(card)
def main(): """Connect to Notcard and run a transaction test.""" print("Opening port...") try: if use_uart: port = busio.UART(board.TX, board.RX, baudrate=9600) else: port = busio.I2C(board.SCL, board.SDA) except Exception as exception: raise Exception("error opening port: " + NotecardExceptionInfo(exception)) print("Opening Notecard...") try: if use_uart: card = notecard.OpenSerial(port) else: card = notecard.OpenI2C(port, 0, 0) except Exception as exception: raise Exception("error opening notecard: " + NotecardExceptionInfo(exception)) # If success, do a transaction loop print("Performing Transactions...") while True: time.sleep(2) transactionTest(card)
def test_read_value(self): import adafruit_blinka adafruit_blinka.patch_system( ) # needed before adafruit_gps imports time import microcontroller.pin gc.collect() import busio gc.collect() import adafruit_gps gc.collect() # configure the last available UART (first uart often for REPL) uartId, uartTx, uartRx = microcontroller.pin.uartPorts[0] uart = busio.UART(uartTx, uartRx, baudrate=9600, timeout=3000) gps = adafruit_gps.GPS(uart) gps.send_command("PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") gps.send_command("PMTK220,1000") def try_fix(): gps.update() return gps.has_fix await_true("GPS fix", try_fix) self.assertTrue(gps.satellites is not None) self.assertTrue(-90 <= gps.latitude < 90) self.assertTrue(-180 <= gps.longitude < 180)
def UART(): global _UART if not _UART: _UART = busio.UART(TX, RX) return _UART
def init_gps(): global gps RX = board.RX TX = board.TX uart = busio.UART(TX, RX, baudrate=9600, timeout=3000) gps = adafruit_gps.GPS(uart, debug=False) gps.send_command(b'PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0') gps.send_command(b'PMTK220,1000')
def connect(self): self.uart = None try: uart = busio.UART(board.TX, board.RX, baudrate=115200) self.uart = uart except: return 1 return 0
def main_loop(): while True: led.value = True led.value = False for baudrate in BAUDRATES: uart = busio.UART(board.D0, board.D4, baudrate=baudrate, timeout=TIMEOUT) testecho(uart, 0) uart.deinit() uart = busio.UART(board.D4, board.D0, baudrate=baudrate, timeout=TIMEOUT) testecho(uart, 1) uart.deinit()
def run_test( pins: Sequence[str], tx_pin: str = TX_PIN_NAME, rx_pin: str = RX_PIN_NAME, baud_rate: int = BAUD_RATE, ) -> Tuple[str, List[str]]: """ Performs random writes out of TX pin and reads on RX. :param list[str] pins: list of pins to run the test on :param str tx_pin: pin name of UART TX :param str rx_pin: pin name of UART RX :param int baudrate: the baudrate to use :return: tuple(str, list[str]): test result followed by list of pins tested """ # Echo some values over the UART if list(set(pins).intersection(set([tx_pin, rx_pin]))): # Tell user to create loopback connection print("Connect a wire from TX to RX. Press enter to continue.") input() # Initialize UART uart = busio.UART(getattr(board, tx_pin), getattr(board, rx_pin), baudrate=baud_rate) uart.reset_input_buffer() # pylint: disable=no-member # Generate test string test_str = "" for _ in range(NUM_UART_BYTES): test_str += chr(random.randint(ASCII_MIN, ASCII_MAX)) # Transmit test string uart.write(bytearray(test_str)) print("Transmitting:\t" + test_str) # Wait for received string data = uart.read(len(test_str)) recv_str = "" if data is not None: recv_str = "".join([chr(b) for b in data]) print("Received:\t" + recv_str) # Release UART pins uart.deinit() # Compare strings if recv_str == test_str: return PASS, [tx_pin, rx_pin] return FAIL, [tx_pin, rx_pin] # Else (no pins found) print("No UART pins found") return NA, []
def __enter__(self): self.device = busio.UART(tx=board.ESP_RX, rx=board.ESP_TX, \ baudrate=115200, timeout=1, receiver_buffer_size=1024) reset = DigitalInOut(board.ESP_WIFI_EN) reset.switch_to_output(value=True, drive_mode=DriveMode.OPEN_DRAIN) self.reset_pin = reset return self
def __init__(self, ADS1248, mcpArr, tmpArr, buzzer, relay, fan): self.mode = 0 # 0 = idle, 1 = chg/dschg/storage, 2 = shutdown BMS.ADS1248 = ADS1248 ADS1248.wakeupAll() ADS1248.wregAll(2, [0x40, 0x03]) print("[INFO] Calibrating ADCs.") ADS1248.selfOffsetAll() self.cellCount = 20 self.drain = [0] * 24 self.mcpArr = mcpArr for mcp in self.mcpArr: mcp.iodir = 0x00 mcp.gpio = 0x00 self.uart = busio.UART(board.TX, board.RX, baudrate=9600) self.tmpArr = tmpArr self.temps = [0] * len(tmpArr) self.maxTemp = 80 self.fanTrigger = 40 self.fan = fan self.buz = buzzer self.relay = relay self.cellPos = [ 18, 15, 12, 6, 3, 9, 0, 7, 16, 13, 10, 19, 1, 4, 20, 17, 11, 5, 2, 14 ] self.cells = [0] * self.cellCount self.minVoltage = 3.4 self.maxVoltage = 4.25 self.targetVoltage = 3.85 self.dV = .01 self.balTime = 32 self.testBalCount = 0 self.error = False self.dot = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.1) # self.log = open("battVoltages.log", "w") self.verbose = False if microcontroller.nvm[0] == 1: print( "[ALERT] A measurement error or severe battery error occured during previous operation." ) microcontroller.nvm[0] = 0 self.getCells() self.lastCells = list(self.cells)
def __init__(self, ioBusy): self.uart = busio.UART(board.TX, board.RX, baudrate=9600) self.pinBusy = digitalio.DigitalInOut(ioBusy) self.pinBusy.direction = digitalio.Direction.INPUT self.bufCmd = bytearray(10) self.bufCmd[0] = 0x7E # marca do inicio self.bufCmd[1] = 0xFF # versao do protocolo self.bufCmd[2] = 6 # tamanho dos dados self.bufCmd[4] = 0 # nao queremos resposta self.bufCmd[9] = 0xEF # marca do fim
def __init__(self, tx, rx, baud_rate, echo=False): self._uart = busio.UART( tx, rx, baudrate=baud_rate, timeout=0, receiver_buffer_size=self._RX_BUFFER_LEN, ) self._rx_buffer = bytearray(self._RX_BUFFER_LEN) self._blocking_reader = self.create_blocking_reader( baud_rate) if echo else None
def __init__(self): # Define RX and TX pins for the board's serial port connected to the GPS. # These are the defaults you should use for the GPS FeatherWing. # For other boards set RX = GPS module TX, and TX = GPS module RX pins. RX = board.RX TX = board.TX self.gps_dict = { 'has_fix': True, 'Latitude': 0.0, 'Longitude': 0.0, 'fix_quality': '', 'year': 0, 'month': 0, 'day': 0, 'hour': 0, 'minute': 0, 'second': 0, 'satellites': 0, 'altitude': 0.0, 'speed': 0.0, 'latitude': 0.0, 'longitude': 0.0, 'fix_quality': '' } # Create a serial connection for the GPS connection using default speed and # a slightly higher timeout (GPS modules typically update once a second). self.uart = busio.UART(TX, RX, baudrate=9600, timeout=30) # for a computer, use the pyserial library for uart access # import serial # uart = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=3000) # Create a GPS module instance. self.gps = adafruit_gps.GPS(self.uart, debug=False) self.gps_has_fix = False # Initialize the GPS module by changing what data it sends and at what rate. # These are NMEA extensions for PMTK_314_SET_NMEA_OUTPUT and # PMTK_220_SET_NMEA_UPDATERATE but you can send anything from here to adjust # the GPS module behavior: # https://cdn-shop.adafruit.com/datasheets/PMTK_A11.pdf # Turn on the basic GGA and RMC info (what you typically want) self.gps.send_command(b'PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0') # Turn on just minimum info (RMC only, location): # gps.send_command(b'PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0') # Turn off everything: # gps.send_command(b'PMTK314,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0') # Tuen on everything (not all of it is parsed!) # gps.send_command(b'PMTK314,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0') # Set update rate to once a second (1hz) which is what you typically want. self.gps.send_command(b'PMTK220,1000')
def init_gps(self): """Set up GPS module.""" uart = busio.UART(board.TX, board.RX, baudrate=9600, timeout=3000) gps = adafruit_gps.GPS(uart) time.sleep(1) # https://cdn-shop.adafruit.com/datasheets/PMTK_A11.pdf # Turn on the basic GGA and RMC info (what you typically want), then # set update to once a second: gps.send_command('PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0') gps.send_command('PMTK220,1000') self.gps = gps
def get_printer(): # TODO: print a test page & verify printer class & bandrate ThermalPrinter = adafruit_thermal_printer.get_printer_class(2.69) uart = busio.UART(TX, RX, baudrate=19200) printer = ThermalPrinter(uart, auto_warm_up=False) printer.warm_up() printer.upside_down = True printer.size = adafruit_thermal_printer.SIZE_SMALL printer.justify = adafruit_thermal_printer.JUSTIFY_LEFT return printer
def __init__(self, rx, tx, *, baudrate=38400, timeout=250, buffer_size=100): self._uart = busio.UART(tx, rx, baudrate=baudrate, timeout=timeout) self._buffer = bytearray(buffer_size) self._frame_ptr = 0 self._command_header = bytearray(3) if not self._run_command(_RESET, bytes([0x00]), 5): raise RuntimeError( 'Failed to get response from VC0706, check wiring!')
def __init__(self): # Set up the UART connection to the BeagleBone self.uart = busio.UART(board.TX, board.RX, baudrate=9600) self.startup_flag = False self.handoff_flag = False self.kill_radio_flag = False self.handlers = {} self.parsers = {} # Add parsers self.add_message_parser('PKT', parser_pkt) # Add handlers self.add_message_handler('BST', handler_bst, 3)
def init(bdrate=19200): global iPodUart global MetaData global CmdReqs # global iPodName global PlayStatus global PlayChangeNotification global TrackIndex TrackIndex = 0 PlayStatus = True PlayChangeNotification = False iPodMode = 0 CmdReqs = [] iPodUart = busio.UART(board.TX, board.RX, baudrate=bdrate, timeout=0.3)