Serial (UART) communication is performed between mac and python3 using a USB serial driver or the like.
You can do this by installing pyserial with pip and import serial. I found a lot of articles in the search that I couldn't do with python3, but as of February 29, 2020, I could do it with python3.
install.sh
$ pip install pyserial
The code is as follows, which receives 1 byte serially, converts it to decimal notation, and converts it to standard output.
serial_read.py
import serial
import struct
ser = serial.Serial(
port = "/dev/cu.usbserial-XXXXXXXX",
baudrate = 115200,
#parity = serial.PARITY_NONE,
#bytesize = serial.EIGHTBITS,
#stopbits = serial.STOPBITS_ONE,
#timeout = None,
#xonxoff = 0,
#rtscts = 0,
)
while True:
if ser.in_waiting > 0:
recv_data = ser.read(1)
print(type(recv_data))
a = struct.unpack_from("B",recv_data ,0)
print( a )
The port string should be ls /dev/cu.*
, and select the appropriate device from the devices that appear as ʻusbserial -...`. The commented out part retains the default settings, so comment it out and set the appropriate parameters if necessary.
You can check if there is received data in the serial buffer (the number of bytes contained in the buffer) by referring to ser.in_waiting
.
The received data will be treated as a character string even if it is binary data. If the received data is binary, you need to convert it to a number using struct_unpack_from ()
as in the code above. If it is a utf8 string, you need to decode it. If it is a so-called 7bit character string, it can be treated as a character string as it is without decoding or unpacking.
Send any byte string (buf).
serial_write.py
import serial
import struct
def send( buf ):
while True:
if ser.out_waiting == 0:
break
for b in buf:
a = struct.pack( "B", b )
ser.write(a)
ser.flush()
ser = serial.Serial(
port = "/dev/cu.usbserial-XXXXXXXX",
baudrate = 115200,
#parity = serial.PARITY_NONE,
#bytesize = serial.EIGHTBITS,
#stopbits = serial.STOPBITS_ONE,
#timeout = None,
#xonxoff = 0,
#rtscts = 0,
)
x = [ 0x01, 0xFF, 0x02, 0xFE, 0x03]
send( x )
If you do not flush by yourself, it seems that it will not send until some transmission data is buffered. If you do not check ser.out_waiting
, it seems that sometimes it cannot be sent normally.
If you want to send a (alphanumeric) string instead of a binary, you can do it below.
serial_str_write.py
x = b'abcdef'
ser.write( x )
If you want to send a utf8 string, you need to encode it.
I thought it would be easier than writing in C language or swift, but I did a lot of things other than the communication part, so I had a hard time finding out about unpack and encode.
Recommended Posts