]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/adafruit_blinka/microcontroller/rp2040/uart.py
Merge pull request #518 from makermelissa/main
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / microcontroller / rp2040 / uart.py
1 """UART Class for RP2040"""
2 from machine import UART as _UART
3 from machine import Pin
4 from microcontroller.pin import uartPorts
5
6 # pylint: disable=protected-access, no-self-use
7 class UART:
8     """Custom UART Class for RP2040"""
9
10     # pylint: disable=too-many-arguments
11     def __init__(self, tx, rx, baudrate=9600, bits=8, parity=None, stop=1):
12         # check tx and rx have hardware support
13         for portId, txPin, rxPin in uartPorts:
14             if txPin == tx and rxPin == rx:
15                 self._uart = _UART(
16                     portId,
17                     baudrate,
18                     bits=bits,
19                     parity=parity,
20                     stop=stop,
21                     tx=Pin(txPin.id),
22                     rx=Pin(rxPin.id),
23                 )
24                 break
25         else:
26             raise ValueError(
27                 "No Hardware UART on (tx,rx)={}\nValid UART ports: {}".format(
28                     (tx.id, rx.id), uartPorts
29                 )
30             )
31
32     # pylint: enable=too-many-arguments
33
34     def read(self, nbytes=None):
35         """Read from the UART"""
36         return self._uart.read(nbytes)
37
38     def readinto(self, buf, nbytes=None):
39         """Read from the UART into a buffer"""
40         return self._uart.readinto(buf, nbytes)
41
42     def readline(self):
43         """Read a line of characters up to a newline charater from the UART"""
44         return self._uart.readline()
45
46     def write(self, buf):
47         """Write to the UART from a buffer"""
48         return self._uart.write(buf)