错误:资源暂时不可用无法接收串行数据

时间:2015-10-13 10:14:30

标签: c usb uart

我的C代码正在向Uart发送数据,但在接收它时会出错。 这是我的代码

#include <stdio.h>      // standard input / output functions
#include <stdlib.h>
#include <string.h>     // string function definitions
#include <unistd.h>     // UNIX standard function definitions
#include <fcntl.h>      // File control definitions
#include <errno.h>      // Error number definitions
#include <termios.h>   
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);
/* Error Handling */

if ( USB < 0 )
{
printf( "Error %d form tcgetattr : %s /n", errno, strerror( errno ) );
}

/* Save old tty parameters */
tty_old = 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 );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) 
{
printf("Error %d from tcsetattr /n",errno);
//   std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}

/*  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);

/* READ   */
int n = 0,spot_r =0;
char buf = '\0';

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

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

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

错误消息

Error reading Resource temporarily unavailable

它正在完美地向UART发送数据。 但是在接收方它会给出暂时不可用的资源错误。 我应该延迟吗? 或任何其他可以帮助我的功能。

谢谢。

ABHI

0 个答案:

没有答案