您的位置:首页 > 编程语言 > C语言/C++

C语言实现两台电脑通过串口通信

2013-02-23 13:01 302 查看
用C语言实现在发送端控制台输入字符串并在接收端接收显示的功能。

/*********************server.c****************/
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<termios.h>
#define BAUDRATE B38400
#define MODEMDEVICE "/dev/ttyS0"
#define STOP '@'
int main(){
int fd,c=0,res;
struct termios oldtio,newtio;
char ch,s1[20];
printf("start...\n");
fd=open(MODEMDEVICE,O_RDWR | O_NOCTTY);
if(fd<0)
{
perror(MODEMDEVICE);
exit(1);
}
printf("open...\n");
tcgetattr(fd,&oldtio);
bzero(&newtio,sizeof(newtio));
newtio.c_cflag=BAUDRATE|CS8|CLOCAL|CREAD;
newtio.c_iflag=IGNPAR;
newtio.c_oflag=0;
newtio.c_lflag=ICANON;
tcflush(fd,TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
printf("writing...\n");
while(1)
{
while((ch=getchar())!='@')
{
s1[0]=ch;
res=write(fd,s1,1);
}
s1[0]=ch;
s1[1]='\n';
res=write(fd,s1,2);
break;
}
printf("close...\n");
close(fd);
tcsetattr(fd,TCSANOW,&oldtio);
return 0;
}

/**************client.c***************/
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<termios.h>
#define BAUDRATE B38400
#define MODEMDEVICE "/dev/ttyS0"
int main()
{
int fd,c=0,res;
struct termios oldtio,newtio;
char buf[256];
printf("start ...\n");
fd=open(MODEMDEVICE,O_RDWR | O_NOCTTY);
if(fd<0)
{
perror(MODEMDEVICE);
exit(1);
}
printf("open...\n");
tcgetattr(fd,&oldtio);
bzero(&newtio,sizeof(newtio));
newtio.c_cflag=BAUDRATE | CS8 | CLOCAL | CREAD;
newtio.c_iflag=IGNPAR;
newtio.c_oflag=0;
newtio.c_lflag=ICANON;
tcflush(fd,TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
printf("reading...\n");
while(1)
{
res=read(fd,buf,255);
buf[res]=0;
printf("res=%d vuf=%s\n",res,buf);
if(buf[0]=='a') break;
}
printf("close...\n");
close(fd);
tcsetattr(fd,TCSANOW,&oldtio);
return 0;
}

发送端截图:



接受端截图:



(-----------that's all-----------)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: