从ttyUSB1设备串口读取

时间:2015-11-17 11:53:47

标签: c serial-port tty

你好,我无法使用c程序读取无限循环

以下是我的计划请帮我提前谢谢

如何在串行USB编程中进行无限循环 你好,我无法使用c程序从无限循环读取

以下是我的计划请帮我提前谢谢

如何在串行USB编程中进行无限循环

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>

int main(){
    int fd;
    int n;

    fd = open_port();
    char creadbyte[10];
    char buf[10];
    while(1){
        n = read(fd,creadbyte,1);

        if(creadbyte == '\n'){
            strcat(buf,creadbyte);
            break;
        }
        sleep(2);
    }
    printf("%c",creadbyte);

    close(fd);
}   

int open_port(){  
    int fd; 
    fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY);

    if(fd < 0){
        perror("open_port: Unable to open /dev/ttyUSB1");
    }else
        fcntl(fd, F_SETFL, FNDELAY);

    printf("In Open port fd = %d\n", fd);
    return(fd);

    struct termios options;
    tcgettr(fd, &options);

    cfsetispeed(&options,B9600);
    cfsetospeed(&options,B9600);

    options.c_cflag |= (CLOCAL | CREAD); 
    options.c_cflag &= ~CSIZE; /* Mask the character size bits */
    options.c_cflag |= CS8;    /* Select 8 data bits */   
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    options.c_oflag &= ~OPOST;

    if(tcsetattr(fd, TCSANOW, &options) == -1)
        printf("Error with tcsetattr = %s\n", strerror(errno));
    else
        printf("%s\n", "tcsetattr succeed");

    fcntl(fd, F_SETFL, FNDELAY);

}

0 个答案:

没有答案