How to implement serial communication using python

Foreword
    The friend who wrote the interface for the company has resigned, and I have to take on the next project. Whatever the company needs, we have to make up for it.
**

Table of contents

1. Preparation

**1.1 The concept of host computer and slave computer

1.2 What is the serial port?

1.3 Environment setup

2. Program

2.1 Host computer code

2.2 Lower computer code


1. Preparation

**
1.1 The concept of upper computer and lower computer


        Simply put, the upper computer is the computer that issues commands and is responsible for the issuance of main commands; the lower computer is the computer that executes naming and is responsible for function implementation and error message return. In short, one is the leader (upper computer) and the other is the employee (lower computer).
        The following is the official concept, which can be skipped. The upper computer and the lower computer are two important concepts in distributed systems.
        Host computer usually refers to higher-level computer equipment, such as desktop computers, servers or embedded computers. They are responsible for controlling and managing the entire system, collecting and processing data, and performing complex algorithms and logical operations. The host computer usually runs software programs written in high-level languages ​​and provides a user-friendly graphical interface so that users can interact with the system.
        The lower computer usually refers to lower-level computer equipment, such as microcontrollers, microcontrollers, sensors, etc. They are responsible for performing simple control tasks in the system, collecting sensor data and passing it to the host computer, or executing instructions sent by the host computer. The lower computer usually uses programs written in low-level languages ​​and can directly interact with the hardware.
        In a distributed system, the upper computer and the lower computer communicate through a communication protocol. For example, different communication protocols (such as RS232 serial communication or RS485 serial communication) can be used to realize remote control and monitoring between the upper computer and the lower computer, as well as the acquisition of real-time data and status information.


1.2 What is the serial port?


        Now that both parties are ready, how does the upper computer transmit the command to the lower computer? This involves the data transmission channel, which is the serial communication interface, or COM interface.
        I am using the 232 to USB communication method. You need to install the driver first; the corresponding COM port on the computer will naturally appear! Right-click on the win key and select Device Manager. ![Insert image description here](https://img-blog.csdnimg.cn/487064b5a4854151914f62bdeb13cf84.png)


1.3 Environment setup


        Because my host computer and slave computer are both computers, I installed drivers and serial communication tools on the two devices respectively.
        Note: The main purpose of using serial communication tools is to check for problems with the connection and device hardware. Otherwise, if the python communication code is written incorrectly, it will be classified as a hardware problem.

2. Program

2.1 Host computer code


        The host computer mainly issues instructions.

```python
import serial #导入模块
import time

# 端口号,根据自己实际情况输入,可以在设备管理器查看
port = "COM1"
# 串口波特率,根据自己实际情况输入(232的都是9600)
bps = 9600
# 超时时间,None:永远等待操作,0为立即返回请求结果,其他值为等待超时时间(单位为秒)
# 打开串口,并返回串口对象
ser = serial.Serial(port, bps, timeout=0.1)
# 发送数据的代码
def receive_command():
    data = ser.readline().hex().strip()
    if data != '':
        print('Received:', data)
def send_command(hex_command):
    try:
        # 串口发送一个字符串
        # len = ser.write("hello world".encode('utf-8'))
        command = bytes.fromhex(hex_command)
        len = ser.write(command)
        print("send len: ", len)
        receive_command()
        # 关闭串口
        # ser.close()
    except Exception as result:
        print("******error******:", result)
def main():
    while True:
            # 定时发送数据
            # 关机指令,16进制编码
            hex_command = '24 00 00 00 00 00 00 00 00 00 00 00 00 01 00 01 03 06 66 2A'
            send_command(hex_command)
            # print("send len: ", len)
            time.sleep(10)

main()
```

2.2 Lower computer code


        The lower computer mainly receives instructions.

```python
import serial #导入模块
import time
# 端口号,根据自己实际情况输入,可以在设备管理器查看
port = "COM1"
# 串口波特率,根据自己实际情况输入
bps = 9600
# 超时时间,None:永远等待操作,0为立即返回请求结果,其他值为等待超时时间(单位为秒)

# 打开串口,并返回串口对象
ser = serial.Serial(port, bps, timeout=0.1)
# 发送数据的代码
def receive_command():
    data = ser.readline().hex().strip()
    if data != '':
        print('Received:', data)
def main():
    while True:
            receive_command()
main()
```


3. End
        When the communication between the upper computer and the lower computer is normal, the rest is to complete the corresponding functions based on the command information, then I will develop new functions! !
        
 

Guess you like

Origin blog.csdn.net/qq_25993375/article/details/134271832