Chinaunix首页 | 论坛 | 博客
  • 博客访问: 399679
  • 博文数量: 83
  • 博客积分: 2011
  • 博客等级: 大尉
  • 技术积分: 741
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-04 22:51
文章分类

全部博文(83)

文章存档

2009年(83)

我的朋友

分类:

2009-07-21 21:29:32

接收端程序:
 
#include
#include
#include
#include
#include
#include
#include
#define BAUDRATE B38400
#define MODEMDEVICE "/dev/ttyS1"
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); //目前终端机参数保存至oldtio

 bzero(&newtio, sizeof(newtio)); //清除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); //新的termios 作为通信端口的参数
 
 printf("reading...\n");
 while (1)
 {
  res = read(fd, buf,255);
  buf[res] = 0;
  printf("res = %d, vuf = %s\n", res, buf);
  if (buf[0] ==
)
   break;
 }
 printf("close...\n");
 close(fd);
 tcsetattr(fd, TCSANOW, &oldtio); //恢复旧的端口参数
 return 0;
}
 
 
发送端程序:
 
#include
#include
#include
#include
#include
#include
#include
#define BAUDRATE B38400
#define MODEMDEVICE "/dev/ttyS0"
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("wrinting...\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;
}

 
阅读(755) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~