我正在使用串行交叉索引和環回讀取和寫入串行端口的程序,通過刻錄電纜的第二和第三針腳。我能寫,但無法閱讀。 在讀取輸出中顯示爲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;
}