在网上搜了很多关于树莓派串口通讯的例子,但是都是用python写的,虽然python很有名,而且最近也在学习这门语言,
但是还是想用c语言实现一下,因为需要用到整套系统里,其他内容都是用c语言写的。但是网上没有找打现成的。
还好,之前做过天嵌2440开发板的串口程序(参照天嵌工程师提供的代码),发现串口程序其实是通用的,
驱动层屏蔽了硬件细节,个人猜测,几乎所有移植好的系统的串口,都可以用一样的代码来操作,至少2440和树莓派是通用的。
分享代码如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include"pthread.h"
#include "serial.h"
struct serial_config serialread;
static int serial_fd;
int speed_arr[] = {B230400, B115200, B57600, B38400, B19200, B9600, B4800, B2400, B1200, B300,
B38400, B19200, B9600, B4800, B2400, B1200, B300};
int name_arr[] = {230400, 115200, 57600, 38400, 19200, 9600, 4800, 2400, 1200, 300,
38400, 19200, 9600, 4800, 2400, 1200, 300};
//-----------------------------------------------
//打印配置文件serial.cfg的内容
//-----------------------------------------------
void print_serialread()
{
printf("serialread.dev is %s\n",serialread.serial_dev);
printf("serialread.speed is %d\n",serialread.serial_speed);
printf("serialread.databits is %d\n",serialread.databits);
printf("serialread.stopbits is %d\n",serialread.stopbits);
printf("serialread.parity is %c\n",serialread.parity);
}
//-----------------------------------------------
//读取serial.cfg文件并进行配置
//----------------------------------------------