uart设备的读写,和普通的文件读写没有啥不同,都是open/read/write。
uart参数的设置,有两种接口,一个是ioctl()接口,一个是termios(3)描述的POSIX接口。
有两个结构体用来描述terminals and serial lines。
struct termios
struct termios2
<asm/termbits.h>和<termios.h>都定义了struct termios,且这两个结构体不兼容。
termios接口
       #include <termios.h>
       #include <unistd.h>
       int tcgetattr(int fd, struct termios *termios_p);
       int tcsetattr(int fd, int optional_actions,
                     const struct termios *termios_p);
       int tcsendbreak(int fd, int duration);
       int tcdrain(int fd);
       int tcflush(int fd, int queue_selector);
       int tcflow(int fd, int action);
       void cfmakeraw(struct termios *termios_p);
       speed_t cfgetispeed(const struct termios *termios_p);
       speed_t cfgetospeed(const struct termios *termios_p);
       int cfsetispeed(struct termios *termios_p, speed_t speed);
       int cfsetospeed(struct termios *termios_p, speed_t speed);
       int cfsetspeed(struct termios *termios_p, speed_t speed);
ioctl接口
       #include <sys/ioctl.h>
       #include <asm/termbits.h>   /* Definition of struct termios,
                                      struct termios2, and
                                      Bnnn, BOTHER, CBAUD, CLOCAL,
                                      TC*{FLUSH,ON,OFF} and other constants */
       int ioctl(int fd, int cmd, ...);
Get and set terminal attributes
TCGETS/TCSETS/
TCGETS2/TCSETS2
Get and set window size
TIOCGWINSZ
TIOCSWINSZ
使用ioctl设置波特率等参数的例子:
int uart_set(int fd, struct uart *uart)
{
        struct termios2 tio;
        int ret;
        ret = ioctl(fd, TCGETS2, &tio);
        if (ret)
                return -1; 
    
        if (uart->baud_rate) {
                tio.c_cflag &= ~CBAUD;
                tio.c_cflag |= BOTHER;
                tio.c_ospeed = uart->baud_rate;
                tio.c_cflag &= ~(CBAUD << IBSHIFT);
                tio.c_cflag |= BOTHER << IBSHIFT;
                tio.c_ispeed = uart->baud_rate;
        }
    
        ret = ioctl(fd, TCSETS2, &tio);
        if (ret)
                return -2; 
    
        return 0;
}
man termios
man ioctl_tty