📄 com.c
字号:
#include "com.h"
int comfd;
static struct termios oldterm;
int speed_arr[7] = {B230400, B115200, B57600,B38400, B19200, B9600, B4800};
int name_arr[7] = {230400, 115200, 57600, 38400, 19200, 9600, 4800};
int openComm(const com_attr_t *ca)
{
int i=0;
if((comfd = open(ca->com_device,O_RDWR))<0)
{
fprintf(stderr,"COM open Error!\n");
return -1;
}
tcflush(comfd, TCIFLUSH);
struct termios term;
bzero(&term, sizeof(term));
if(tcgetattr(comfd,&oldterm) !=0)
{
fprintf(stderr,"Setup Serial false!\n");
return -1;
}
memcpy(&term,&oldterm,sizeof(oldterm));
/* Set port settings for canonical input processing */
term.c_cflag = CREAD | CLOCAL | HUPCL;
term.c_cflag &= ~ CRTSCTS;
term.c_cflag &= ~ PARODD;
term.c_lflag &= ~ (ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHONL | NOFLSH |ECHOPRT |ECHOCTL | ECHOKE | ECHOK);
term.c_iflag |= IGNPAR;
term.c_iflag &= ~(INLCR | ICRNL | IXON | IXOFF | IXOFF | IUCLC |IXANY |IMAXBEL | IUTF8);
term.c_iflag &= ~IGNBRK;
term.c_oflag &= ~(ONLCR | OLCUC | OCRNL | ONOCR | ONLRET | OFILL | OFDEL);
term.c_oflag &= ~OPOST;
term.c_cc[VMIN] = 150;
term.c_cc[VTIME] = 8;
switch (ca->databits) /*set databits*/
{
case 7:
term.c_cflag |= CS7;
break;
case 8:
term.c_cflag |= CS8;
break;
default:
fprintf(stderr,"Unsupported data size\n"); return -1;
}
switch (ca->parity)
{
case 'n':
case 'N':
term.c_cflag &= ~PARENB; /* Clear parity enable */
term.c_iflag &= ~INPCK; /* Enable parity checking */
break;
case 'o':
case 'O':
term.c_cflag |= (PARODD | PARENB); /* ODD*/
term.c_iflag |= INPCK; /* Disnable parity checking */
break;
case 'e':
case 'E':
term.c_cflag |= PARENB; /* Enable parity */
term.c_cflag &= ~PARODD; /* even*/
term.c_iflag |= INPCK; /* Disnable parity checking */
break;
case 'S':
case 's': /*as no parity*/
term.c_cflag &= ~PARENB;
term.c_cflag &= ~CSTOPB;
break;
default:
fprintf(stderr,"Unsupported parity\n");
return -1;
}
if (ca->stopbits == 1)
{
term.c_cflag &= ~CSTOPB;
}
else
{
term.c_cflag |= CSTOPB;
}
tcflush(comfd, TCIOFLUSH);
//set_speed(comfd,nBaudRate);
for(i=0;i<7;i++)
{
if (ca->baud_rate == name_arr[i])
{
term.c_cflag |= speed_arr[i];
}
}
if (tcsetattr(comfd,TCSANOW,&term) != 0)
{
fprintf(stderr,"SetupSerial 3");
return -1;
}
return comfd;
}
int closeComm()
{
tcsetattr(comfd,TCSANOW,&oldterm);
return close(comfd);
}
int writeComm(void * pData,int nLength)
{
int nWrite;
nWrite=write(comfd,pData,nLength);
if(nWrite == -1)
fprintf(stderr,"Write Com error!\n");
return nWrite;
}
int readComm(void * pData,int nLength)
{
int nread;
nread=read(comfd,pData,nLength);
if (nread == -1)
{
fprintf(stderr,"Read com Error!\n");
return -1;
}
return nread;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -