- 论坛徽章:
- 0
|
vc 设置串口同linux 串口通信。
vc上设置:
m_Com.SetCommPort(1);// 指定串口号
m_Com.SetInBufferSize(16);// 指定接收缓冲区大小
m_Com.SetOutBufferSize(16);
if(!m_Com.GetPortOpen())
m_Com.SetPortOpen(true);
m_Com.SetInputMode(1);//设置二进制接收模式
m_Com.SetSettings("115200,N,8,1");// 通信参数设置
m_Com.SetRThreshold(1);
m_Com.SetInputLen(0);
m_Com.GetInput();//先预读缓冲区以清除残留数据
//啊 CSuiDlg::OnOK();
linux上如何设置才能同vc串口通信成功呢。
linux 目前设置是:
void set_speed(int fd, int speed){
int status;
struct termios Opt;
tcgetattr(fd, &Opt);
struct Speedtab *sp = speedtab;
for (sp = speedtab; sp->speed; sp++)
if (sp->speed == speed)
{
tcflush(fd, TCIOFLUSH);
printf("sp->speed = %d\n",sp->speed);
cfsetispeed(&Opt, sp->code);
cfsetospeed(&Opt, sp->code);
status = tcsetattr(fd, TCSANOW, &Opt);
if (status != 0) {
perror("tcsetattr fd");
return;
}
tcflush(fd,TCIOFLUSH);
}
}
int set_Parity(int fd,int databits,int stopbits,int parity)
{
struct termios options;
if ( tcgetattr( fd,&options) != 0) {
perror("SetupSerial 1");
return(FALSE);
}
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 (FALSE);
}
switch (parity)
{
case 'n':
case 'N':
options.c_cflag &= ~PARENB; /* Clear parity enable */
options.c_iflag &= ~INPCK; /* Enable parity checking */
break;
case 'o':
case 'O':
options.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/
options.c_iflag |= INPCK; /* Disnable parity checking */
break;
case 'e':
case 'E':
options.c_cflag |= PARENB; /* Enable parity */
options.c_cflag &= ~PARODD; /* 转换为偶效验*/
options.c_iflag |= INPCK; /* Disnable 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 (FALSE);
}
/* 设置停止位*/
switch (stopbits)
{
case 1:
options.c_cflag &= ~CSTOPB;
break;
case 2:
options.c_cflag |= CSTOPB;
break;
default:
fprintf(stderr,"Unsupported stop bits\n");
return (FALSE);
}
/* Set input parity option */
if (parity != 'n')
options.c_iflag |= INPCK;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /*Input*/
options.c_oflag &= ~OPOST; /*Output*/
// options.c_oflag &= ~(ONLCR|OCRNL); /*ADD*/
//
// options.c_iflag &= ~(ICRNL|INLCR); /*ADD*/
// options.c_iflag &= ~(IXON|IXOFF|IXANY); /*ADD*/
//
tcflush(fd,TCIFLUSH);
options.c_cc[VTIME] = 150; /* 设置超时15 seconds*/
options.c_cc[VMIN] = 0; /* Update the options and do it NOW */
if (tcsetattr(fd,TCSANOW,&options) != 0)
{
perror("SetupSerial 3");
return (FALSE);
}
return (TRUE);
}
set_speed(listen_fd,115200);
printf("after set_speed listen_fd=%d\n",listen_fd);
if (set_Parity(listen_fd,8,1,'N') == FALSE) {
printf("Set Parity Error\n");
exit (0);
} |
|