News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

2024-11(8)

【Python】python 使用串口

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:

  1. Install the PySerial module

The pyserial module can be installed using the pip command:

pip install pyserial
  1. Import the PySerial module

First import the pyserial module in the python file :

import serial
  1. open serial port

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 COM1is the name of the serial port and 9600is the baud rate.

  1. read data

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.

  1. data input

Use write()the method to write data to the serial port.

ser.write(b'Hello World\n')

Among them, bit means to convert the string into binary data. \nNote that or is added at the end \r\nto indicate the completion of writing a row of data.

  1. close the serial port

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()


Category of website: technical article > Blog

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.

6 0
collect article
collected

Comment content: (supports up to 255 characters)