EMS/drv/drv_uart.c

86 lines
1.9 KiB
C
Raw Normal View History

2024-11-12 08:21:37 +08:00
#include "drv_uart.h"
int drv_uart_open(char *dev, int32_t baudrate, int32_t databit, char parity, char stopbit)
{
int devFd = open(dev, O_RDWR | O_NONBLOCK| O_NOCTTY | O_NDELAY);
if(devFd == -1) {
printf("open uart failed\n");
}
else {
struct termios oldtio, newtio;
memset(&newtio, 0, sizeof(newtio));
speed_t speed;
switch (baudrate)
{
case 9600:
speed = B9600;
break;
case 38400:
speed = B38400;
break;
case 115200:
speed = B115200;
break;
default:
speed = B115200;
break;
}
switch (databit)
{
case 8:
newtio.c_cflag |= CS8;
break;
case 7:
newtio.c_cflag |= CS7;
break;
case 6:
newtio.c_cflag |= CS6;
break;
case 5:
newtio.c_cflag |= CS5;
break;
default:
newtio.c_cflag |= CS8;
break;
}
switch (parity)
{
case 'N':
newtio.c_cflag &= ~PARENB;
break;
case 'E':
newtio.c_cflag |= PARENB;
newtio.c_cflag &= ~PARODD;
break;
case 'O':
newtio.c_cflag |= (PARENB | PARODD);
break;
default:
newtio.c_cflag &= ~PARENB;
break;
}
switch (stopbit)
{
case '1':
newtio.c_cflag &= ~CSTOPB;
break;
case '2':
newtio.c_cflag |= CSTOPB;
default:
newtio.c_cflag &= ~CSTOPB;
break;
}
newtio.c_cflag |= (CLOCAL | CREAD); /* | CRTSCTS */
newtio.c_oflag &= ~OPOST;
newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
newtio.c_cc[VTIME] = 1; /* unit: 1/10 second. */
newtio.c_cc[VMIN] = 255; /* minimal characters for reading */
tcflush(devFd, TCIFLUSH);
tcsetattr(devFd, TCSANOW, &newtio);
}
return devFd;
}