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("Can't 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) {

tcflush(fd, TCIOFLUSH);

cfsetispeed(&Opt, speed_arr);

cfsetospeed(&Opt, speed_arr);

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 ( t

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐