背景
嵌入式Linux开发,绕不开串口操作。
代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <termios.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd = -1;
struct termios options;
struct timeval timeout;
fd_set readfd;
int ret = -1;
char data = 0;
/* open */
fd = open("/dev/ttyS2", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd < 0) {
printf("open serial device error");
return -1;
}
/* get parameters */
if (tcgetattr(fd, &options) != 0) {
printf("tcgetattr error\n");
return -1;
}
/* set band: 115200 */
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
/* set data bits: 8 */
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
/* set parity bits: none */
options.c_cflag &= ~PARENB;
options.c_iflag &= ~INPCK;
/* set stop bits: 1 */
options.c_cflag &= ~CSTOPB;
/* set control */
options.c_cflag |= (CLOCAL|CREAD);
/* set input and output */
options.c_oflag &= ~OPOST;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
/* set wait time */
options.c_cc[VTIME] = 0;
options.c_cc[VMIN] = 0;
/* save the config */
tcflush(fd, TCIFLUSH);
if (tcsetattr(fd, TCSANOW, &options) != 0) {
perror("tcsetattr");
return -1;
}
timeout.tv_sec = 10;
timeout.tv_usec = 100000;
FD_ZERO(&readfd);
FD_SET(fd, &readfd);
while (1) {
FD_SET(fd, &readfd);
ret = select(fd+1, &readfd, NULL, NULL, &timeout);
if (ret > 0) {
if (FD_ISSET(fd, &readfd)) {
ret = read(fd, &data, 1);
if (ret > 0) {
printf("%d\n", data);
}
}
}
}
return 0;
}
参考
https://blog.csdn.net/donglicaiju76152/article/details/49962631