2015-10-14 68 views
1

我使用USB to Uart轉換器來傳輸和接收我的數據。 這裏是我的傳輸碼錯誤errno 11資源暫時不可用

void main() 
{ 
int USB = open("/dev/ttyUSB0", O_RDWR | O_NONBLOCK | O_NDELAY);   
struct termios tty; 
struct termios tty_old; 
memset (&tty, 0, sizeof tty); 

/* Set Baud Rate */ 
cfsetospeed (&tty, (speed_t)B9600); 
cfsetispeed (&tty, (speed_t)B9600); 

/* Setting other Port Stuff */ 
tty.c_cflag  &= ~PARENB;   // Make 8n1 
tty.c_cflag  &= ~CSTOPB; 
tty.c_cflag  &= ~CSIZE; 
tty.c_cflag  |= CS8; 

tty.c_cflag  &= ~CRTSCTS;   // no flow control 
tty.c_cc[VMIN] = 1;     // read doesn't block 
tty.c_cc[VTIME] = 5;     // 0.5 seconds read timeout 
tty.c_cflag  |= CREAD | CLOCAL;  // turn on READ & ignore ctrl lines 

/* Make raw */ 
cfmakeraw(&tty); 

/* Flush Port, then applies attributes */ 
tcflush(USB, TCIFLUSH); 

/* WRITE */ 
unsigned char cmd[] = "YES this program is writing \r"; 
int n_written = 0,spot = 0; 
do { 
n_written = write(USB, &cmd[spot], 1); 
spot += n_written; 
} while (cmd[spot-1] != '\r' && n_written > 0); 

爲expacted

YES this program is writing 

現在,這是我從UART

閱讀
/* READ */ 
int n = 0,spot1 =0; 
char buf = '\0'; 

/* Whole response*/ 
char response[1024]; 
memset(response, '\0', sizeof response); 

do { 
n = read(USB, &buf, 1); 
sprintf(&response[spot1], "%c", buf); 
spot1 += n; 
} while(buf != '\r' && n > 0); 

if (n < 0) { 
printf("Error reading %d %s",errno, strerror(errno)); 
} 
else if (n==0) { 
printf("read nothing"); 
} 
else { 
printf("Response %s",response); 
} 
} 

這個讀數來自UART的代碼我的代碼的輸出是相同的從errno給出錯誤,它是錯誤號11,表示資源暫時不可用

我得到這個輸出

Error reading 11 Resource temporarily unavailable 

我使用USB轉UART轉換器。希望有人能幫助。謝謝:)

回答

0

您從read調用中收到錯誤代碼EAGAIN,這導致您退出循環並打印出錯誤。當然,EAGAIN意味着這是一個暫時的問題(例如,當您嘗試閱讀時沒有任何要閱讀的內容,也許您想稍後嘗試?)。

你可以重組的讀取是相似的:

n = read(USB, &buf, 1) 
if (n == 0) { 
    break; 
} else if (n > 0) { 
    response[spot1++] = buf; 
} else if (n == EAGAIN || n == EWOULDBLOCK) 
    continue; 
} else { /*unrecoverable error */ 
    perror("Error reading"); 
    break; 
} 

你可以通過使buf是一個數組和閱讀在時間超過一個字符改善你的代碼。另請注意,sprintf是不必要的,您可以將字符複製到數組中。

+0

AKA'我把它設置爲非阻塞,並且當它沒有阻止時感到驚訝':) –

+0

它顯示錯誤:繼續語句不在循環內 –

+0

嗯......你在做什麼?循環?你刪除了循環? –

相關問題