Linux下操作串口

背景

嵌入式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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值