linux 串口应用层API

#include<termios.h>

struct termios  oldtio, newtio;


        fd = open(“/dev/tty0”, O_RDWR|O_NOCTTY);

     tcgetattr(fd, &oldtio);//获取终端参数,在进行设置串口参数之前必须先获取。
    bzero(&newtio, sizeof(newtio));
newtio = oldtio;

//设置波特率
switch(pSysInfo->rs485.Baudrate)
{


case 0:
cfsetispeed(&newtio, B300);
cfsetospeed(&newtio, B300);
break;
case 1:
cfsetispeed(&newtio, B600);
cfsetospeed(&newtio, B600);
break;
case 2:
cfsetispeed(&newtio, B1200);
cfsetospeed(&newtio, B1200);
break;
case 3:
cfsetispeed(&newtio, B2400);
cfsetospeed(&newtio, B2400);
break;
case 4:
cfsetispeed(&newtio, B9600);
cfsetospeed(&newtio, B9600);
break;
case 5:
cfsetispeed(&newtio, B19200);
cfsetospeed(&newtio, B19200);
break;
case 6:
cfsetispeed(&newtio, B38400);
cfsetospeed(&newtio, B38400);
break;
case 7:
cfsetispeed(&newtio, B57600);
cfsetospeed(&newtio, B57600);
break;
case 8:
cfsetispeed(&newtio, B115200);
cfsetospeed(&newtio, B115200);
break;
default:
printf("bauldrate set wrong\n");


}

//设置数据位
switch(pSysInfo->rs485.Databits)
{
case 8:
newtio.c_cflag&=~CSIZE;
newtio.c_cflag |=CS8;
break;
case 7:
newtio.c_cflag&=~CSIZE;
newtio.c_cflag |=CS7;
break;
case 6:
newtio.c_cflag&=~CSIZE;
newtio.c_cflag |=CS6;
break;
case 5:
newtio.c_cflag&=~CSIZE;
newtio.c_cflag |=CS5;
break;
default:
printf("databits set wrong\n");
}
//设置停止位
if(pSysInfo->rs485.Stopbit == 1)
{
newtio.c_cflag &= ~CSTOPB;
}else if(pSysInfo->rs485.Stopbit == 2)
{
newtio.c_cflag |= CSTOPB;
}else
{
printf("Stopbit set wrong\n");

}


//设置奇偶校验位
switch(pSysInfo->rs485.Paritybit)
{
case 0:
newtio.c_cflag &= ~PARENB;
break;
case 1:
newtio.c_cflag |= (PARODD | PARENB);
break;
case 2:
newtio.c_cflag &= ~ PARENB;
newtio.c_cflag &= ~PARODD;
break;
case 3:
newtio.c_cflag &= ~PARENB;
newtio.c_cflag &= ~CSTOPB;
break;
default:
printf("Paritybit set wrong\n");

}


//设置流控
switch(pSysInfo->rs485.FlowControl)
{
case 0:
newtio.c_cflag &= ~CRTSCTS;
break;
case 1:
newtio.c_cflag |= CRTSCTS;
break;
case 2:
newtio.c_cflag |= IXON|IXOFF|IXANY;
break;
default:
printf("FlowControl set wrong\n");
}


cfmakeraw(&newtio);

    tcflush(fd, TCIOFLUSH);
    tcsetattr(fd, TCSANOW, &newtio);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值