串口通信协议实现.doc
文本预览下载声明
这几天,由于长春门检系统项目的需要,涉及到了读卡器信息的串口读取,所以在Linux下串口信息的读取有了一点心得体会。
1. 打开串口
与其他的关于设备编程的方法一样,在Linux下,操作、控制串口也是通过操作起设备文件进行的。在Linux下,串口的设备文件是/dev/ttyS0或/dev/ttyS1等。因此要读写串口,我们首先要打开串口:
char *dev = /dev/ttyS0; //串口1
int fd = open( dev, O_RDWR );
//| O_NOCTTY | O_NDELAY
if (-1 == fd)
{
perror(Cant Open Serial Port);
return -1;
}
else
return fd;
2. 设置串口速度
打开串口成功后,我们就可以对其进行读写了。首先要设置串口的波特率:
int speed_arr[] = { B38400, B19200, B9600, B4800, B2400, B1200, B300,
B38400, B19200, B9600, B4800, B2400, B1200, B300, };
int name_arr[] = {38400, 19200, 9600, 4800, 2400, 1200, 300, 38400,
19200, 9600, 4800, 2400, 1200, 300, };
void set_speed(int fd, int speed){
int i;
int status;
struct termios Opt;
tcgetattr(fd, Opt);
for ( i= 0; i 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 fd);
return;
}
tcflush(fd,TCIOFLUSH);
}
}
}
3. 设置串口信息
这主要包括:数据位、停止位、奇偶校验位这些主要的信息。
/**
*@brief 设置串口数据位,停止位和效验位
*@param fd 类型 int 打开的串口文件句柄
*@param databits 类型 int 数据位 取值 为 7 或者8
*@param stopbits 类型 int 停止位 取值为 1 或者2
*@param parity 类型 int 效验类型 取值为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);
显示全部