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

    /*********************server.c****************/  
   #include<stdio.h>
#include <stdlib.h> //exit()
#include <strings.h>//bzero()
#include <unistd.h> //close()
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<termios.h>
#define BAUDRATE B115200
#define MODEMDEVICE "/dev/ttyUSB0"
#define STOP '@'
int main(){
   int fd,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 <stdlib.h> //exit()
#include <strings.h>//bzero()
#include <unistd.h> //close()
#include<sys/types.h>
#include<fcntl.h>
#include<termios.h>
#define BAUDRATE B115200
#define MODEMDEVICE "/dev/ttyUSB0"
int main()
{
    int fd,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;//char buf[ ],'\0' = 0;
       printf("res=%d vuf=%s\n",res,buf);
       if(buf[0]=='*') break;
    }
       printf("close...\n");
       close(fd);
       tcsetattr(fd,TCSANOW,&oldtio);
       return 0;
}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值