Linux中的串口(Serial Port)是一种用于数据传输的接口,通常用于连接外部设备,如调制解调器、GPS设备等。串口通信基于RS-232标准,是一种异步通信协议。
/dev/ttyS0
、/dev/ttyS1
等。/dev/ttyUSB0
、/dev/ttyUSB1
等。/dev/tty
。以下是一个简单的Linux串口读写示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int main(int argc, char *argv[]) {
int fd;
struct termios options;
char buffer[256];
if (argc != 2) {
fprintf(stderr, "Usage: %s <serial_port>\n", argv[0]);
exit(1);
}
fd = open(argv[1], O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("open_port: Unable to open serial port");
return -1;
}
// 设置串口参数
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
tcsetattr(fd, TCSANOW, &options);
// 写入数据
char *data = "Hello, Serial Port!";
write(fd, data, strlen(data));
// 读取数据
int n = read(fd, buffer, sizeof(buffer));
if (n > 0) {
buffer[n] = '\0';
printf("Received: %s\n", buffer);
} else {
perror("read");
}
close(fd);
return 0;
}
通过以上信息,您应该能够理解Linux串口读写的基础概念、优势、类型、应用场景以及常见问题及其解决方法。
领取专属 10元无门槛券
手把手带您无忧上云