2011-10-05 61 views
2

我正在使用串行交叉索引和环回读取和写入串行端口的程序,通过刻录电缆的第二和第三针脚。我能写,但无法阅读。 在读取输出中显示为0。由它读取的字节数。它不显示为-1的错误。从串口读取和写入,通过Linux中的环回

#include <stdio.h> // standard input/output functions 
#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> // POSIX terminal control definitionss 
#include <time.h> // time calls 
#include <sys/ioctl.h> 


int open_port(void) 
    { 
    int fd; // file description for the serial port 

    fd = open("/dev/ttyS1", O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); 

    if(fd == -1) // if open is unsucessful 
{ 
perror("open_port: Unable to open /dev/ttyS0 - "); 
} 
else 
{ 
fcntl(fd, F_SETFL, 0); 
} 
printf("%d",fd); 
return(fd); 
} 
    int configure_port(int fd)  // configure the port 
{ 
struct termios port_settings;  // structure to store the port settings in 

cfsetispeed(&port_settings, B9600); // set baud rates 
cfsetospeed(&port_settings, B9600); 
port_settings.c_cflag |= (CLOCAL | CREAD); 

port_settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits 
port_settings.c_cflag &= ~CSTOPB; 
port_settings.c_cflag &= ~CSIZE; 
port_settings.c_cflag |= CS8; 
tcflush(fd, TCIOFLUSH); 
tcsetattr(fd, TCSANOW, &port_settings); // apply the settings to the port 
return(fd); 

    } 
int main() 
{ 
int fd= open_port(); 
int d=configure_port(fd); 
printf("%d",d); 
int bytes; 

char mk[10]; 
scanf("%s",&mk); 
int w=write(fd,mk,strlen(mk)); 

int y=ioctl(fd,FIONREAD,&bytes); 

printf("%d\n",w); 
perror("write"); 
printf("%d",y); 
char buffer[80]; 
char *data; 
int nbytes; 

data=buffer; 
nbytes=read(fd,data,5); 
printf("the outputis \n%d\n\n",nbytes); 
perror("read"); 
while(nbytes > 0) 
{printf("datmukun %d\n\n",nbytes); 
data+=nbytes; 
if (data[-1]=='\n'||data[-1]=='\r') 
break; 
} 
return 0; 
} 

回答

0

根据您的TTY驱动程序的O_NDELAYO_NONBLOCK可引起read在非阻塞的行为方式。因此,您拨打read时很可能尚未收到数据。如果您删除这些标志,则应该在read中阻止,直到至少有一个字符可用。

0

您必须等待一段时间才能使数据可用。通过创建使用while循环和里面一个sleep()功能,可能是一个计数器来尝试了许多次小的延迟测试的目的

  • 很干脆,只是:你可以做到这一点像下面这样。
  • 您可以在文件描述符上使用select()函数,让您的进程进入休眠状态一段时间,并在数据可用或达到超时时收到通知。
相关问题