串口通信
参考 Serial Programming Guide for POSIX Operating System 和树莓派的 WiringPi 代码。关于串口的介绍可以看 STM32。
Linux 与 STM32 不同。32 本质上是操作寄存器,但是 Linux 本着一切设备皆文件的理念,串口操作也是通过文件的‘读’与‘写’完成。串口在 Linux 下 /dev/tty*
打开串口
使用 Linux open(2) 函数。参数一般选择:
O_RDWR
: 串口读写O_NOCTTY
: 放弃对/dev/tty*
端口控制。如果没有设置的话,端口的输入会影响当前进程。O_NDELAY
: Noblocking Mode。如果没有设置的话,在 RS232 DCD 为低时,当前进程会休眠(无数据时阻塞了当前进程)。
Example
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
/*
* 'open_port()' - Open serial port 1.
*
* Returns the file descriptor on success or -1 on error.
*/
int
open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/ttyf1", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
/*
* Could not open the port.
*/
perror("open_port: Unable to open /dev/ttyf1 - ");
}
else
fcntl(fd, F_SETFL, 0);
return (fd);
}