利用tty串口通信

#define ACU_TTY_USB ("/dev/ttyS0")

static int create_acu_fd(void)
{
    int fd = 0;

if ((fd = open(ACU_TTY_USB, O_RDWR | O_NOCTTY | O_SYNC)) < 0)   //打开/dev/ttyS0口,使用标志O_NOCTTY | O_SYNC     
{                
    syslog(LOG_ERR, "open file %s error:%s", ACU_TTY_USB, strerror(errno));
    return -1;        
}

if (set_tty_params(fd, 115200, 'N', 8, 1, 0, 0) < 0)
{
    close(fd);
    return -1;
}

    return fd; 
}

static int set_tty_params(int fd, long baudr, char par, int bit, int stopb, int hwf, int swf)
{
    int ret = -1;
    unsigned int speed = 0;
    struct termios newtty;

memset(&newtty, 0, sizeof(struct termios));
ret = tcgetattr(fd, &newtty);
if (ret != 0)
{
	syslog(LOG_ERR, "tcgetattr error:%s", strerror(errno));
	return -1;
}

switch(baudr)
{
        case 2400:      speed = B2400; break;
        case 9600:      speed = B9600; break;
        case 19200:     speed = B19200; break;
        case 38400:     speed = B38400; break;
        case 57600:     speed = B57600; break;
        case 115200:    speed = B115200; break;
        case 230400:    speed = B230400; break;
        default:        speed = B38400; break;
}

ret = cfsetispeed(&newtty, (speed_t)speed);
ret = cfsetospeed(&newtty, (speed_t)speed);

switch (bit)
{
    case 5:
            newtty.c_cflag |= (newtty.c_cflag & ~CSIZE) | CS5;
            break;
    case 6:
            newtty.c_cflag |= (newtty.c_cflag & ~CSIZE) | CS6;
            break;
    case 7:
            newtty.c_cflag |= (newtty.c_cflag & ~CSIZE) | CS7;
            break;
    case '8':
    default:
            newtty.c_cflag |= (newtty.c_cflag & ~CSIZE) | CS8;
            break;
}

newtty.c_iflag =  IGNBRK;
newtty.c_lflag = 0;
newtty.c_oflag = 0;
newtty.c_cflag |= CLOCAL | CREAD;
newtty.c_cc[VMIN] = 1;
newtty.c_cc[VTIME] = 5;

newtty.c_cflag &= ~(PARENB | PARODD);
switch(par)
{
        case 'E': 
                newtty.c_cflag |= PARENB;
                newtty.c_iflag |= (INPCK | ISTRIP);
                break;
        case 'O':
                newtty.c_cflag |= PARENB;
                newtty.c_cflag |= PARODD;
                newtty.c_iflag |= (INPCK | ISTRIP);
                break;
        case 'N':
        default:
                break;
}

if (stopb == 2)
    newtty.c_cflag |= CSTOPB;
else
    newtty.c_cflag &= ~CSTOPB;

if (swf)
    newtty.c_iflag |= IXON | IXOFF;
else
    newtty.c_iflag &= ~(IXON|IXOFF|IXANY);

ret = tcsetattr(fd, TCSANOW, &newtty);
if (ret != 0)
{
    syslog(LOG_ERR, "tcsetattr error:%s", strerror(errno));
	return -1;
}

    return 0;
}

linux tty设置详解

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值