本文章是基于创龙的 T113-MiniEVM 的开发板和 HC-05 蓝牙模块进行实验的。
main.c 代码
#include "serial.h"
volatile bool g_quit = false;
void sig_handle(int arg) {
g_quit = true;
}
int main()
{
int fd_serial, fd_key;
int ret;
//打开串口4
fd_serial = open_port("/dev/ttyAS4");
//无法打开串口,退出程序
if(fd_serial < 0)
{
return -1;
}
serial_init(fd_serial);
/* Ctrl+c handler */
signal(SIGINT, sig_handle);
int size = 8;
char *msg = NULL;
while(!g_quit)
{
ret = read(fd_serial, msg, size);
if(ret != -1)
{
printf("result: %d, msg: %s\n", ret, msg);
}
}
free(msg);
close(fd_serial);
return 0;
}
serial.h 代码
#ifndef _SERIAL_H_
#define _SERIAL_H_
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <asm/ioctls.h>
#include <termios.h>
#include <sys/stat.h>
#include <limits.h>
//打开串口
int open_port(char *serialName);
int serial_init(int fd);
#endif
serial.c 代码
#include "serial.h"
//打开串口
int open_port(char *serialName)
{
int fd;
fd = open(serialName, O_RDWR | O_NOCTTY | O_NONBLOCK);//O_NONBLOCK设置为非阻塞模式,在read时不会阻塞住,在读的时候将read放在while循环中
//printf("fd=%d\n",fd);
if(fd == -1)
{
perror("Can't Open SerialPort");
}
return fd;
}
int serial_init(int fd)
{
struct termios options; //定义一个termios的结构体变量,此时options是个随机值
tcgetattr(fd, &options); //获取文件描述符的配置信息,类似于配置寄存器的操作,读改写
options.c_cflag |= ( CLOCAL | CREAD ); //CLOCAL忽略调制解调状态行,目的是保证应用程序不会占用串口,CREAD启用接收装置
options.c_cflag &= ~CSIZE; //CSIZE数据位长度的掩码,先设置清空,然后置为8
options.c_cflag |= CS8; //设置数据位为8,可选的值有 CS5、CS6、CS7、CS8
options.c_cflag &= ~CRTSCTS; //CRTSCTS的含义是启用硬件流控制,这里关闭硬件流控制
options.c_cflag &= ~CSTOPB; //CSTOPB表示送两个停止位,否则为1位,这里是&= ~CSTOPB是一个停止位的意思
options.c_iflag |= IGNPAR; // 忽略奇偶校验
options.c_iflag &= ~(ICRNL | IXON); // ICRNL将输入的CR转换成NL,IXON使启动/停止输出控制流起作用 ,这里是把这两个功能取消
options.c_oflag = 0;
options.c_lflag = 0;
cfsetispeed(&options, B9600); //设置输入的波特率
cfsetospeed(&options, B9600); //设置输出的波特率
//调用tcsetattr,使上述配置生效
if(tcsetattr(fd, TCSANOW, &options) < 0)
{
perror("SerialPort init failure");
return -1;
}
return 0;
}
安装蓝牙模块
将 HC-05 蓝牙模块的 TX 和 RX 与 T113 开发板的 TX 和 RX 交叉相连。因为代码中是使用uart4,所以在开发板中连接着 uart4 的 TX 和 RX 端口。
实验结果
通过手机连接蓝牙模块,然后通过蓝牙助手发送数据,可以看到开发板成功接受到手机发送的数据。注意这里手机使用的蓝牙助手为 HC-05 商家提供。