1. 程式人生 > >usb轉串列埠非同步讀取資料

usb轉串列埠非同步讀取資料

該實驗是通過usb轉串列埠線連線了開發板的 uart3和pc。

在pc上編譯下面程式碼並執行


#include<stdio.h>
#include <signal.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <unistd.h>

#define MODEMDEVICE "/dev/ttyUSB0"
#define FALSE 0
#define TRUE 1

int wait_flag=TRUE;

void signal_handler(int i){

    printf("%s\n", __func__);
    wait_flag=TRUE; 
}

int main(){
    
    int fd=0;
    int res;
    char buf[512]={0};
    int STOP = 1;

    fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY | O_NONBLOCK);
            if (fd <0) {perror(MODEMDEVICE); return -1; }

    signal(SIGIO, signal_handler);
     /* allow the process to receive SIGIO */
    fcntl( fd, F_SETOWN, getpid() );
    
    int flags = fcntl( fd, F_GETFL );
        
    fcntl( fd, F_SETFL, flags|FASYNC );
    
    while(STOP){

        if(wait_flag){
            res = read(fd,buf,512);
            buf[res]='\0';
            printf("%d : %s\n", res, buf);
            if(buf[0]=='s' && buf[1] =='t'){
                STOP = 0;
            }
            wait_flag=FALSE;
        }
        //sleep(1);
    }

    printf("exit...\n");
    
    close(fd);

    return 0;
}

執行效果: