#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;
}
利用tty串口通信
最新推荐文章于 2023-04-23 18:18:46 发布