串行通讯程序怎么用

时间:2025-01-17 17:05:30 游戏攻略

串行通讯程序的用法取决于你使用的编程语言和平台。以下是几种常见编程语言的串行通讯程序用法:

Python 使用 PySerial 库

安装 PySerial 库

```bash

pip install pyserial

```

基本使用

```python

import serial

创建串口对象

ser = serial.Serial('COM3', 9600) Windows 系统用 COM3, Linux 用 /dev/ttyUSB0

发送数据

ser.write(b'hello') 记得用字节类型

读取数据

data = ser.read(5)

print(data)

关闭串口

ser.close()

```

Linux 下使用 C 语言

接收数据

```c

include

include

include

include

include

include

include

int main() {

int ser_port = open("/dev/ttyS0", O_RDONLY);

if (ser_port < 0) {

perror("open");

return 1;

}

struct termios tty;

if (tcgetattr(ser_port, &tty) != 0) {

perror("tcgetattr");

return 1;

}

tty.c_cflag &= ~PARENB; // 关闭奇偶校验

tty.c_cflag &= ~CSTOPB; // 关闭停止位

tty.c_cflag &= ~CSIZE;

tty.c_cflag |= CS8; // 8 位数据位

tty.c_cflag &= ~CRTSCTS; // 关闭 CRTS/CTS

tty.c_cflag |= CREAD | CLOCAL; // 启用接收和忽略控制线

tty.c_lflag &= ~ICANON;

tty.c_lflag &= ~ECHO; // 关闭回显

tty.c_lflag &= ~ECHOE; // 关闭 erasure

tty.c_lflag &= ~ECHONL; // 关闭 new-line echo

tty.c_lflag &= ~ISIG; // 关闭特殊字符的识别

tty.c_iflag &= ~(IXON | IXOFF | IXANY); // 关闭自动换行和流控制

tty.c_oflag &= ~OPOST; // 关闭输出缓冲

tty.c_oflag &= ~ONLCR; // 关闭将换行符转换为回车符

cfsetispeed(&tty, B9600);

cfsetospeed(&tty, B9600);

if (tcsetattr(ser_port, TCSANOW, &tty) != 0) {

perror("tcsetattr");

return 1;

}

char buffer;

while (1) {

ssize_t len = read(ser_port, buffer, sizeof(buffer) - 1);

if (len < 0) {

perror("read");

break;

}

buffer[len] = '\0';

printf("Received: %s\n", buffer);

}

close(ser_port);

return 0;

}

```

发送数据