用C编写一个Linux环境下串口的应用串口的波特率是1152008位数据位1位停止位
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <termios.h>
#define BAUDRATE B115200 #define DEVICE "/dev/ttyS0"
int main() { int fd; struct termios options;
fd = open(DEVICE, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
fcntl(fd, F_SETFL, 0);
tcgetattr(fd, &options);
cfsetispeed(&options, BAUDRATE);
cfsetospeed(&options, BAUDRATE);
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;
options.c_cc[VMIN] = 1;
options.c_cc[VTIME] = 0;
tcsetattr(fd, TCSANOW, &options);
char msg[] = "Hello, Serial Port!\n";
write(fd, msg, strlen(msg));
char buf[255];
int n = read(fd, buf, 255);
buf[n] = '\0';
printf("%s", buf);
close(fd);
return 0;
原文地址: https://www.cveoy.top/t/topic/eoj7 著作权归作者所有。请勿转载和采集!