串口通信是一种常见的异步通信方式,广泛应用于嵌入式系统、物联网设备等领域。在Linux系统中,串口通信可以通过中断接收和轮询接收两种方式进行。
在Linux系统中,可以通过设置串口的中断接收模式来实现中断接收。以下是一个简单的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char **argv)
{
int fd;
struct termios oldtio, newtio;
char buf[256];
if (argc != 2) {
fprintf(stderr, "Usage: %s <device>\n", argv[0]);
exit(1);
}
fd = open(argv[1], O_RDWR | O_NOCTTY);
if (fd < 0) {
perror("open");
exit(1);
}
tcgetattr(fd, &oldtio); /* save old port settings */
newtio = oldtio; /* copy old settings */
cfsetispeed(&newtio, B9600); /* set baud rate */
cfsetospeed(&newtio, B9600);
newtio.c_cflag |= (CLOCAL | CREAD); /* enable receiver and set local mode */
newtio.c_cflag &= ~PARENB; /* no parity */
newtio.c_cflag &= ~CSTOPB; /* 1 stop bit */
newtio.c_cflag &= ~CSIZE;
newtio.c_cflag |= CS8; /* 8 data bits */
newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* raw input mode */
newtio.c_iflag &= ~(IXON | IXOFF | IXANY); /* no software flow control */
newtio.c_oflag &= ~OPOST; /* raw output mode */
tcsetattr(fd, TCSANOW, &newtio); /* set new port settings */
// Enable serial port interrupts
fcntl(fd, F_SETFL, FNDELAY); // Non-blocking mode
while (1) {
int n = read(fd, buf, sizeof(buf));
if (n > 0) {
printf("Received data: %s\n", buf);
memset(buf, 0, sizeof(buf)); // Clear the buffer
}
}
close(fd);
return 0;
}
串口中断接收是一种高效的串口通信方式,适用于需要实时响应的场景。通过正确设置串口参数和中断处理程序,可以实现稳定可靠的串口通信。
领取专属 10元无门槛券
手把手带您无忧上云