从串口读取和写入,通过linux中的c环回

时间:2011-10-05 09:02:14

标签: c linux serial-port

我正在使用串行交叉电缆和环回来读取和写入串口的程序,通过连接电缆的第2和第3针。我能够写但无法阅读。 在读取输出中,它显示0为否。它读取的字节数。它没有将错误显示为-1。

#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;
}

2 个答案:

答案 0 :(得分:0)

O_NDELAYO_NONBLOCK可能导致read以非阻塞方式运行,具体取决于您的TTY驱动程序。因此,在您拨打read时,很可能没有收到数据。如果删除这些标志,则应在read中阻止,直到至少有一个字符可用。

答案 1 :(得分:0)

您必须等待一段时间才能使数据可用。你可以这样做:

  • 非常简单,只是为了测试目的,通过在其中使用while循环和sleep()函数创建一个小延迟,可能还有一个计数器尝试多次。
  • 您可以在文件描述符上使用select()函数让您的进程暂停一段时间,并在数据可用或超时时收到通知。