|
下面是我用到的代码 read.c用于读取com1数据,write.c用向com2写数据,用3根线接线方式把com1、com2对接。两种设置速率的方式都试过只要将BAUDRATE改为非B9600即出现错误的结果。当BAUDRATE为9600 时数据传输正常。在Xterm4.0和redhat7.0下测试情况相同。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <errno.h>
#include <sys/ioctl.h>
#define BAUDRATE B9600
#define SERIALDEVICE "/dev/ttyS0"
#define FALSE 0
#define TRUE 1
volatile int STOP=FALSE;
main()
{
int serialport,res,i,num_fd,datalen,maxfd;
struct termios oldtio,newtio;
unsigned char buf[255];
fd_set allset,rset;
serialport = open(SERIALDEVICE, O_RDWR | O_NOCTTY );
if (serialport <0) {perror(SERIALDEVICE); exit(-1); }
fcntl(serialport,F_SETFL,FNDELAY);
FD_ZERO(&allset);
FD_SET(serialport,&allset);
tcgetattr(serialport,&oldtio); /* save current port settings */
tcgetattr(serialport,&newtio);
bzero(&newtio, sizeof(newtio));
newtio.c_cflag = CRTSCTS | CS8 | CLOCAL | CREAD;
//设置速率方式之一,或用cfsetispeed()、cfsetospeed()来设置速率
//newtio.c_cflag =BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
newtio.c_iflag = 0;
newtio.c_oflag = 0;
/* set input mode (non-canonical, no echo,...) */
newtio.c_lflag = 0;
newtio.c_cc[VTIME] = 0; /* inter-character timer unused */
newtio.c_cc[VMIN] = 1; /* blocking read until 5 chars received */
cfsetispeed(&newtio,BAUDRATE);
cfsetospeed(&newtio,BAUDRATE);
tcflush(serialport, TCIFLUSH);
tcsetattr(serialport,TCSANOW,&newtio);
//以上是对串口的设置
//从串口读数据并显示
maxfd=serialport;
while (STOP==FALSE) { /* loop for input */
rset=allset;
num_fd=select(maxfd+1,&rset,NULL,NULL,NULL);
if(FD_ISSET(serialport,&rset)){
ioctl(serialport,FIONREAD,&datalen);
printf("enter select");
res = read(serialport,buf,datalen);
printf("Data form serialport:%d BYTE:",datalen);
for(i=0;i<res;i++){
printf(":%02X",(unsigned char)buf);}
printf("\n");
if (res>50) STOP=TRUE;
}
}
tcsetattr(serialport,TCSANOW,&oldtio);
} |
|