用下面的代码收串口的数据,收到的字节数对,可是数据不对是乱码。会是什么问题呢?代码如下:
int SetupCOM(int com, long baud, int parity, int databit,int stopbit)
{
int fd;
char path[20];
U32 comflag=0;
struct termios termios_p;
switch ( com )
{
case COM1:
strcpy(path,"/dev/ser1");
break;
case COM2:
strcpy(path,"/dev/ser2");
break;
default:
break;
}
set the baud rates to speed /
cfsetispeed(options,speed);
cfsetospeed(options,speed);
/
enable the receiver and set local mode
*/
options->c_cflag |= (CLOCAL | CREAD);
}
串口数据位设置
static void serial_port_character_size_set(int data_size,struct termios options)
{
/
mask the character size bits
*/
options->c_cflag &= ~CSIZE;
switch(data_size)
{
case 5:
options->c_cflag |= CS5;
break;
case 6:
options->c_cflag |= CS6;
break;
case 7:
options->c_cflag |= CS7;
break;
case 8:
options->c_cflag |= CS8;
break;
default:
printf(“error data size config!\n”);
exit(EXIT_FAILURE);
}
}
串口校验位设置
static void serial_port_parity_set(char parity_mode,struct termios *options)
{
switch(parity_mode)
{
case ‘n’:
case ‘N’:
options->c_cflag &= ~PARENB;//clear parity enable
options->c_iflag &= ~INPCK;//disable parity checking
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’:
options->c_cflag &= ~PARENB;
options->c_cflag &= ~CSTOPB;
break;
default:
printf(“unsupported parity\n”);
exit(EXIT_FAILURE);
}
}
串口停止位设置
static void serial_port_stop_set(int stopbits,struct termios options)
{
switch(stopbits)
{
case 1:
options->c_cflag &= ~CSTOPB;
break;
case 2:
options->c_cflag |= CSTOPB;
break;
default:
printf(“unsupported stop bits\n”);
exit(EXIT_FAILURE);
}
}
对上面几个设置函数的封装
void serial_port_config(int fd,int speed,int data_size,
char parity_mode,int stopbits)
{
struct termios options;
/
get the current options for the port /
tcgetattr(fd,&options);
/
do what you want /
serial_port_speed_set(speed,&options);
serial_port_character_size_set(data_size,&options);
serial_port_parity_set(parity_mode,&options);
serial_port_stop_set(stopbits,&options);
/