串口通信

串口通信

 

最近做了串口传送数据的实验,主要是设置设置串口传输速度,串口属性参数,对其初始化后,便可以用相应的文件描述符来读取与发送数据。具体代码如下:

/***********************************************
*Function:      set_speed
*Description:  设置串口传输速度
*Input:      fd  串口的句柄
*speed 串口传输速度 

***********************************************/
int set_speed(int fd, int speed)
{
 struct termios opt;

 if (tcgetattr(fd, &opt) != 0) {
  printf("tcgetattr %s/n", strerror(errno));
  return -10;
 }

 tcflush(fd, TCIOFLUSH);
 cfsetispeed(&opt, speed);
 cfsetospeed(&opt, speed);
 tcsetattr(fd, TCSANOW, &opt);
 tcflush(fd, TCIOFLUSH);

 return 0;
}

/***********************************************

*Function:      set_parity
*Description:  设置串口参数
*Input:      fd  串口的句柄
*databits 数据位
*stopbits 停止位
*parity  奇偶校验  
 ***********************************************/
int set_parity(int fd, int databits, int stopbits, int parity)
{
 struct termios opt;

 if (tcgetattr(fd, &opt) != 0) {
  printf("tcgetattr %s/n", strerror(errno));
  return -10;
 }

 opt.c_cflag &= ~CSIZE; /* 不按位数据位掩码 */
 opt.c_cflag |= CS8;
 opt.c_cflag &= ~PARENB; /* Clear parity enable */
 opt.c_iflag &= ~INPCK; /* disable parity checking */
 opt.c_cflag &= ~CSTOPB;/* one stopbit */

 opt.c_cc[VTIME] = 50; /* 5 seconds */
 opt.c_cc[VMIN] = 0;
 opt.c_lflag &= ~(ECHO|ECHOE|ISIG|ICANON);
 opt.c_oflag &= ~OPOST;
 opt.c_iflag &= ~(IXON|IXOFF|INLCR|IGNCR|ICRNL);

 tcflush(fd,TCIFLUSH); /* Update options NOW */
 tcsetattr(fd,TCSANOW,&opt);

 return 0;
}

int init_uart(int number)
{
 int fd;
 char name[16] = { 0, };

 sprintf(name, "/dev/ttyS%d", number);

 fd = open(name, O_RDWR);
 if (fd == -1) {
  UARTERR("Device %s not found/n", name);
  return -1;
 } else {
  UARTINFO("Open device %s/n", name);
 }

 set_speed(fd, B115200);
 set_parity(fd, 8, 1, 'n');

 return fd;
}
初始化完成后,便可以通过read(uartfd, &buff, length),write(uartfd, buf, length);进行串口通信,接收与传送数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值