简单uart通信

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>
#include <stdlib.h>
#include <pthread.h>

int open_port()
{
    int fd;
    if((fd = open("/dev/ttyS0", O_RDWR|O_NOCTTY|O_NDELAY)) < 0){
        perror("Open serial error.");
        return -1;
    }

    return fd;
}

int uart_set(int fd)
{
    struct termios new_cfg, old_cfg;
    if(tcgetattr(fd, &old_cfg) != 0){
        perror("tcgetattr");
        return -1;
    }

    new_cfg = old_cfg;
    cfmakeraw(&new_cfg);
    new_cfg.c_cflag &= ~CSIZE;

    cfsetispeed(&new_cfg, B115200);
    cfsetospeed(&new_cfg, B115200);

    new_cfg.c_cflag |= CS8;

    new_cfg.c_cflag &= ~PARENB;
    new_cfg.c_iflag &= ~INPCK;

    new_cfg.c_cflag &= ~CSTOPB;

    new_cfg.c_cc[VTIME] = 0;
    new_cfg.c_cc[VMIN] = 0;

    tcflush(fd, TCIFLUSH);

    if((tcsetattr(fd, TCSANOW, &new_cfg)) != 0){
        perror("tcsetattr");
        return -1;
    }
    return 0;
}

void *uart_write(void *d)
{
    char buff[100];
    int tfd = *(int *)d;    //文件描述符
    while(1){
        memset(buff, 0, sizeof(buff));
        if(fgets(buff, sizeof(buff), stdin) == NULL){
            break;
        }
        //fgets(buff, sizeof(buff), stdin);
        write(tfd, buff, strlen(buff));
    }
}

int main()
{
    int ret = 0;
    int fd;
    char buff[100];

    pthread_t id,id2;


    if((fd = open_port()) < 0){
        perror("open_port");
        return 1;
    }

    if(uart_set(fd) < 0){
        perror("uart_set");
        return 1;
    }

    ret = pthread_create(&id, NULL, uart_write, &fd);

    while(1){
        memset(buff, 0, sizeof(buff));
        if(read(fd, buff, sizeof(buff)) > 0){
            printf("%s", buff);
        }

    }

    close(fd);
    
    return 0;

}

 

简单uart通信

上一篇:Error creating bean with name '***': Injection of resource dependencies failed,Bean named 'redisService' is expected to be of type


下一篇:fetch 简单封装,并使用