读书人

,如何用C写串口通信的程序啊没有思路,

发布时间: 2012-03-11 18:15:39 作者: rapoo

请教各位大虾,怎么用C写串口通信的程序啊!没有思路,非常感谢!!
请教各位大虾,怎么用C写串口通信的程序啊!没有思路,非常感谢!!

[解决办法]
#include <stdio.h >
#include <string.h >
#include <stdlib.h >
#include <unistd.h >
#include <sys/types.h >
#include <sys/stat.h >
#include <fcntl.h >
#include <termios.h >
#include <errno.h >
int main(void)
{
int fd;
int nwrite, nread, i=0 ,j=0,k;
char qq[256];
struct termios newtio, oldtio;

fd = open( "/dev/ttyS1 ", O_RDWR, 0666);
if(fd == -1)
perror( "open serial 1\n ");

tcgetattr(fd, &oldtio);

bzero(&newtio, sizeof( newtio));

/********************************************/
newtio.c_cflag ¦= (CLOCAL ¦ CREAD);
newtio.c_cflag &=~CSIZE;
newtio.c_cflag ¦= CS8;
newtio.c_cflag &=~PARENB;
cfsetispeed(&newtio, B28800);
cfsetospeed(&newtio, B28800);
newtio.c_cflag &=~CSTOPB;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;
tcflush(fd, TCIFLUSH);
if(tcsetattr(fd, TCSANOW, &newtio) != 0 )
{ perror( "tcsetattr error ");
return -1;
}
/********************************************/

printf( "fd = %d \n ",fd);
printf( "ready for sending command-------\n ");

for(i=0;i <128;i++)
{ qq[i] = '0 ';
printf( " < '%c ' ",qq[i]) ;
}

sleep(1); // 不加 sleep(1) ,则每次只能读4.5个数据
fflush(stdout);
nread = read(fd, qq, 128);
printf( "nread = %d\n ",nread) ;

for(i=0;i <100;i++)
{ printf( " < '%c ' ",qq[i]) ;
}

printf( "\n ");
if(nread == -1)
{printf( " read error!\n ");
}


fflush(stdout);
close(fd);
return 0;

}


刚在其它linux版看到的

读书人网 >C语言

热点推荐