94 lines
2.8 KiB
C
94 lines
2.8 KiB
C
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
#include <string.h>
|
||
#include <unistd.h>
|
||
#include <fcntl.h>
|
||
#include <errno.h>
|
||
#include <termios.h>
|
||
#include <sys/time.h>
|
||
|
||
#define SERIAL_PORT "/dev/ttyS0" // 根据你的设备修改串口设备文件路径
|
||
|
||
int main() {
|
||
int serial_fd;
|
||
struct termios options;
|
||
char *port = SERIAL_PORT;
|
||
char readbuffer[256];
|
||
fd_set readfds;
|
||
struct timeval timeout;
|
||
|
||
// 打开串口
|
||
serial_fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
|
||
if (serial_fd == -1) {
|
||
perror("open_port: Unable to open device");
|
||
return -1;
|
||
}
|
||
|
||
// 获取当前串口设置
|
||
tcgetattr(serial_fd, &options);
|
||
|
||
// 设置波特率
|
||
cfsetispeed(&options, B9600);
|
||
cfsetospeed(&options, B9600);
|
||
|
||
// 设置串口参数:8位数据位,1位停止位,无奇偶校验位
|
||
options.c_cflag &= ~PARENB; // Clear parity bit, no parity
|
||
options.c_cflag &= ~CSTOPB; // Clear stop field, only one stop bit used in communication
|
||
options.c_cflag &= ~CSIZE; // Clear all the size bits
|
||
options.c_cflag |= CS8; // 8 data bits
|
||
options.c_cflag &= ~CRTSCTS; // Disable RTS/CTS hardware flow control
|
||
options.c_lflag &= ~ICANON;
|
||
options.c_lflag &= ~ECHO; // Disable echo
|
||
options.c_lflag &= ~ECHOE; // Disable erasure
|
||
options.c_lflag &= ~ECHONL; // Disable new-line echo
|
||
options.c_lflag &= ~ISIG; // Disable interpretation of INTR, QUIT and SUSP
|
||
options.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl
|
||
options.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR); // Disable special handling of received bytes
|
||
|
||
// 设置输入输出的VMIN和VTIME
|
||
options.c_cc[VMIN] = 0;
|
||
options.c_cc[VTIME] = 5;
|
||
|
||
// 应用串口参数
|
||
tcsetattr(serial_fd, TCSANOW, &options);
|
||
|
||
printf("Configuring the serial port completed\n");
|
||
|
||
// 发送数据
|
||
char *msg = "Hello, Serial Port!\n";
|
||
write(serial_fd, msg, strlen(msg));
|
||
|
||
// 使用select等待数据
|
||
while (1) {
|
||
FD_ZERO(&readfds);
|
||
FD_SET(serial_fd, &readfds);
|
||
|
||
// 设置超时时间
|
||
timeout.tv_sec = 5; // 5 seconds
|
||
timeout.tv_usec = 0;
|
||
|
||
// 等待串口数据,超时返回
|
||
int ret = select(serial_fd + 1, &readfds, NULL, NULL, &timeout);
|
||
if (ret == -1) {
|
||
perror("select error");
|
||
break;
|
||
} else if (ret == 0) {
|
||
printf("select timeout\n");
|
||
continue;
|
||
} else {
|
||
if (FD_ISSET(serial_fd, &readfds)) {
|
||
memset(readbuffer, 0, sizeof(readbuffer));
|
||
int n = read(serial_fd, readbuffer, sizeof(readbuffer));
|
||
if (n > 0) {
|
||
printf("Data Received: %s", readbuffer);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 关闭串口
|
||
close(serial_fd);
|
||
|
||
return 0;
|
||
}
|