注意事项:
- 要使用串行端口,请使用标准系统调用open()打开串行设备,并将设备路径和标志作为参数传递。
- 使用termios库的某些功能,获取串行端口属性并配置通信参数和其他属性。此示例使用相当常见的9600 / 8N1配置,代表波特率为9600波特,8个数据位,无奇偶校验位和1个停止位。
- 使用标准系统调用write()和read()来写入和读取串行端口。首先,刷新接收缓冲区以丢弃旧数据。然后,将字符串存储到缓冲区变量中并将其写入串行端口。
- 写入串口后,您可以从中读取。由于它是一个环回,你将阅读你刚才写的内容并将其保存到缓冲区变量中。此外,请不要忘记在完成后使用标准系统调用close()来关闭设备。为避免计时问题,请在写入和读取之间使用延迟。
#include <stdio.h> /* I/O Definitions */
#include <unistd.h> /* Standard Symbolic Constants */
#include <fcntl.h> /* File Control Definitions */
#include <termios.h> /* POSIX Terminal Control Definitions */
#include <string.h> /* String Manipulation Definitions */
#include <errno.h> /* Error Code Definitions */
int main(int argc, char *argv[])
{
char buf_rx[100];
char buf_tx[100];
const char *device = "/dev/ttymxc1";
struct termios tty;
int fd;
int flags = O_RDWR | O_NOCTTY | O_NDELAY; /* O_RDWR Read/write access to the serial port */
/* O_NOCTTY No terminal will control the process */
/* O_NDELAY Use non-blocking I/O */
/*------------------------------- Opening the Serial Port -------------------------------*/
fd = open(device, flags);
if(fd == -1){
printf("\n Failed to open port! ");
return -1;
}
/*---------- Serial port settings using the termios structure --------- */
/* Settings (9600/8N1):
Baud rate: 9600 baud
Data bits: 8
Parity bit: No
Stop bit: 1
Hardware Flow Control: No
*/
tcgetattr(fd, &tty); /* Get the current attributes of the Serial port */
cfsetispeed(&tty, B9600); /* Set read speed as 9600 baud */
cfsetospeed(&tty, B9600); /* Set write speed as 9600 baud */
tty.c_cflag &= ~PARENB; /* Disables the Parity Enable bit(PARENB) */
tty.c_cflag &= ~CSTOPB; /* Clear CSTOPB, configuring 1 stop bit */
tty.c_cflag &= ~CSIZE; /* Using mask to clear data size setting */
tty.c_cflag |= CS8; /* Set 8 data bits */
tty.c_cflag &= ~CRTSCTS; /* Disable Hardware Flow Control */
if((tcsetattr(fd, TCSANOW, &tty)) != 0){ /* Write the configuration to the termios structure*/
printf("Error! Can't set attributes.\n");
return -1;
}else{
printf("All set! \n");
}
tcflush(fd, TCIFLUSH);
strncpy(buf_tx, "Testing UART\n", sizeof(buf_tx));
int result = write(fd,(char *)buf_tx,sizeof(buf_tx));
if(result == -1){
printf("Error: %s\n",strerror(errno));
return -1;
} else {
printf("%d bytes sent\n", result);
}
usleep(182000);
if (read(fd, buf_rx, sizeof(buf_rx)) == -1) {
printf("Error: %s\n",strerror(errno));
return -1;
}
printf("buf_rx = %s\n", buf_rx);
close(fd);
return 0;
}