#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <assert.h>
const int speed_arr[] = {B230400,B115200,B57600,B38400,B19200,B9600,B4800,B2400,B1800,B1200,B600,B300};
const int name_arr[] = { 230400, 115200, 57600, 38400, 19200, 9600, 4800, 2400, 1800, 1200, 600, 300};
int open_uart(const char *devname)
{
//int fd = open(devname, O_RDWR | O_NOCTTY | O_NDELAY);
int fd = open(devname, O_RDWR);
if(fd < 0)
{
printf("uart port open failure\n");
return -1;
}
return fd;
}
int set_uart_speed(int fd, int speed)
{
int i;
int status;
struct termios Opt;
tcgetattr(fd, &Opt);
for ( i= 0; i < (int)(sizeof(speed_arr) / sizeof(int)); i++) {
if (speed == name_arr[i]) {
tcflush(fd, TCIOFLUSH);
cfsetispeed(&Opt, speed_arr[i]);
cfsetospeed(&Opt, speed_arr[i]);
status = tcsetattr(fd, TCSANOW, &Opt);
if(status != 0) {
perror("tcsetattr fd1");
return -1;
}
tcflush(fd,TCIOFLUSH);
return 0;
}
}
return -1;
}
/**
*@brief set uart databits,stopbits
*@param fd
*@param databits 7,8
*@param stopbits 1,2
*@param parity N,E,O,S
*/
int set_Parity(int fd,int databits,int stopbits,int parity)
{
struct termios options;
if(tcgetattr( fd,&options) != 0) {
perror("SetupSerial 1");
return -1;
}
options.c_cflag &= ~CSIZE;
switch (databits)
{
case 7:
options.c_cflag |= CS7;
break;
case 8:
options.c_cflag |= CS8;
break;
default:
fprintf(stderr,"Unsupported data size\n");
return -1;
}
switch (parity)
{
case 'n':
case 'N':
options.c_cflag &= ~PARENB; /* Clear parity enable */
options.c_iflag &= ~INPCK; /* Enable parity checking */
options.c_iflag = IGNPAR;
break;
case 'o':
case 'O':
options.c_cflag |= (PARODD | PARENB);
options.c_iflag |= INPCK; /* Disable parity checking */
break;
case 'e':
case 'E':
options.c_cflag |= PARENB; /* Enable parity */
options.c_cflag &= ~PARODD;
options.c_iflag |= INPCK; /* Disable parity checking */
break;
case 'S':
case 's': /*as no parity*/
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
break;
default:
fprintf(stderr,"Unsupported parity\n");
return -1;
}
switch (stopbits)
{
case 1:
options.c_cflag &= ~CSTOPB;
break;
case 2:
options.c_cflag |= CSTOPB;
break;
default:
fprintf(stderr,"Unsupported stop bits\n");
return -1;
}
/* Set input parity option */
if (parity != 'n')
options.c_iflag |= INPCK;
tcflush(fd,TCIFLUSH);
options.c_cc[VTIME] = 1;
options.c_cc[VMIN] = 1;
options.c_cflag |= HUPCL | CREAD | CLOCAL;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /*Input*/
options.c_oflag &= ~OPOST; /*Output*/
if (tcsetattr(fd,TCSANOW,&options) != 0)
{
perror("SetupSerial");
return -1;
}
return 0;
}
void close_uart(int fd)
{
if(fd >=0 ){
close(fd);
}
}