posted on 2023-06-06 10:41 read(282) comment(0) like(6) collect(5)
You can use the PySerial module to operate the serial port with Python. Here is an example of usage:
The pyserial module can be installed using the pip command:
pip install pyserial
First import the pyserial module in the python file :
import serial
To open a serial port using serial.Serial()
the method , you need to specify the port number and baud rate.
ser = serial.Serial('COM1', 9600)
where COM1
is the name of the serial port and 9600
is the baud rate.
Use read()
the method to read data from the serial port. For example, the following code can be used when reading a row of data:
line = ser.readline().decode('utf-8').rstrip()
print(line)
Among them, decode('utf-8')
it means to decode the binary data into a string; rstrip()
the method is to remove the blank characters at the end of the string.
Use write()
the method to write data to the serial port.
ser.write(b'Hello World\n')
Among them, b
it means to convert the string into binary data. \n
Note that or is added at the end \r\n
to indicate the completion of writing a row of data.
When the serial port is no longer needed, it should be closed.
ser.close()
Full code example:
import serial
ser = serial.Serial('COM1', 9600)
while True:
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.write(b'Hello World\n')
ser.close()
Author:Abstract
link:http://www.pythonblackhole.com/blog/article/80079/f5d5b8e38c7fdf46c75b/
source:python black hole net
Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.
name:
Comment content: (supports up to 255 characters)
Copyright © 2018-2021 python black hole network All Rights Reserved All rights reserved, and all rights reserved.京ICP备18063182号-7
For complaints and reports, and advertising cooperation, please contact vgs_info@163.com or QQ3083709327
Disclaimer: All articles on the website are uploaded by users and are only for readers' learning and communication use, and commercial use is prohibited. If the article involves pornography, reactionary, infringement and other illegal information, please report it to us and we will delete it immediately after verification!