蓝牙可以当作无线串口使用。使用USB-TTL连接,上电前按住小按键进入AT模式(慢闪,小红灯每2秒闪烁一次),打开串口助手,选择波特率为38400即可发送AT指令到蓝牙。
常用配置:
AT+NAME=名字 AT+ROLE=1(主机模式) AT+ROLE=0(从机模式)
AT+PSWD=1234 AT+ORGL(恢复出场设置) AT+ADDR?(查询B蓝牙的地址)
AT+UART=9600,0,0(设置波特率)
连接单片机串口2,正常上电(没有按小按键,快闪,每1秒闪一次),使用手机蓝牙助手连接该蓝牙,若蓝牙每2秒闪一次,一次连续闪亮下则表示配对成功。
usart2.c配置,波特率默认为9600
#include "sys.h"
#include "usart.h"
//
//Èç¹ûʹÓÃucos,Ôò°üÀ¨ÏÂÃæµÄÍ·Îļþ¼´¿É.
#if SYSTEM_SUPPORT_OS
#include "includes.h" //ucos ʹÓÃ
#endif
u8 res; //ÉèÖÃÈ«¾Ö±äÁ¿
//#define tbuf 50
void My_USART2_Init(void)
{
GPIO_InitTypeDef GPIO_InitStrue;
USART_InitTypeDef USART_InitStrue;
NVIC_InitTypeDef NVIC_InitStrue;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);//GPIO¶Ë¿ÚʹÄÜ
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);//´®¿Ú¶Ë¿ÚʹÄÜ
GPIO_InitStrue.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStrue.GPIO_Pin=GPIO_Pin_2;
GPIO_InitStrue.GPIO_Speed=GPIO_Speed_10MHz;
GPIO_Init(GPIOA,&GPIO_InitStrue);
GPIO_InitStrue.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_InitStrue.GPIO_Pin=GPIO_Pin_3;
GPIO_InitStrue.GPIO_Speed=GPIO_Speed_10MHz;
GPIO_Init(GPIOA,&GPIO_InitStrue);
USART_InitStrue.USART_BaudRate=9600;
USART_InitStrue.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
USART_InitStrue.USART_Mode=USART_Mode_Tx|USART_Mode_Rx;
USART_InitStrue.USART_Parity=USART_Parity_No;
USART_InitStrue.USART_StopBits=USART_StopBits_1;
USART_InitStrue.USART_WordLength=USART_WordLength_8b;
USART_Init(USART2,&USART_InitStrue);
USART_Cmd(USART2,ENABLE); //ʹÄÜ´®¿Ú2
USART_ITConfig(USART2,USART_IT_RXNE,ENABLE);//¿ªÆô½ÓÊÕÖжÏ
NVIC_InitStrue.NVIC_IRQChannel=USART2_IRQn;
NVIC_InitStrue.NVIC_IRQChannelCmd=ENABLE;
NVIC_InitStrue.NVIC_IRQChannelPreemptionPriority=0;
NVIC_InitStrue.NVIC_IRQChannelSubPriority=1;
NVIC_Init(&NVIC_InitStrue);
}
//u8 RX_buffer[tbuf];
//u8 RX_num=0;
void USART2_IRQHandler(void)
{
if(USART_GetITStatus(USART2,USART_IT_RXNE)!=RESET)
{
res= USART_ReceiveData(USART2);
//USART_SendData(USART2,res); //´®¿Ú2·¢ËÍÊý¾Ý¸øÀ¶ÑÀÄ£¿é½ÓÊÕ£¬Ò²¾ÍÊÇÊÖ»úapp½ÓÊÕµ½µÄÊý¾Ý
}
}
主函数,通过手机端发送“1”(ascii格式)拉低PB5电平,并且单片机向蓝牙模块(也可以理解为手机)发送“abcdefg”,发送“2”拉低PB5电平
#include "led.h"
#include "delay.h"
#include "key.h"
#include "sys.h"
#include "usart.h"
#include "usart2.h"
extern u8 res; //ÉèÖÃÍⲿȫ¾Ö±äÁ¿
int main(void)
{
int i;
char a[]="abcdefg";
delay_init(); //ÑÓʱº¯Êý³õʼ»¯
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //ÉèÖÃNVICÖжϷÖ×é2:2λÇÀÕ¼ÓÅÏȼ¶£¬2λÏìÓ¦ÓÅÏȼ¶
uart_init(115200); //´®¿Ú³õʼ»¯Îª115200
LED_Init(); //LED¶Ë¿Ú³õʼ»¯
KEY_Init();
My_USART2_Init();
while(1)
{
if(res=='1')
{
GPIO_ResetBits(GPIOB,GPIO_Pin_5); //PA.1ָʾµÆÁÁ
delay_ms(500); //¼ÙÈçÒªÓÃÑÓʱº¯Êý£¬×îºÃ¾ÍÔÚÉÏÃæ³õʼ»¯ÑÓʱº¯Êý£¬²»È»³ÌÐòºÜÈÝÒ×¾ÍÅÜ·É
for(i=0;i<7;i++)
{
USART_SendData(USART2, a[i]); //Ïò´®¿Ú2·¢ËÍÊý¾Ý¸øÀ¶ÑÀÄ£¿é
while(USART_GetFlagStatus(USART2,USART_FLAG_TC)!=SET);//µÈ´ý·¢ËͽáÊø
}
res=0;
}
if(res=='2')
{
GPIO_SetBits(GPIOB,GPIO_Pin_5); //PA.1ָʾµÆÃð
res=0;
}
}
}