给我一段keil代码使用stm32的hal库版本连接jdy-09蓝牙模块,并向手机小程序发送字符串”蓝牙已连接“。
时间: 2024-05-27 10:10:52 浏览: 114
HAL库蓝牙发送,低功耗解决方案,基于stm32f407_嵌入式/单片机编程
#include "main.h"
#include "usart.h"
#include "gpio.h"
#include "stm32f1xx_hal.h"
#define JDY09_UART huart1
#define JDY09_BUF_SIZE 64
UART_HandleTypeDef JDY09_UART;
uint8_t JDY09_RX_BUF[JDY09_BUF_SIZE];
uint8_t JDY09_RX_LEN = 0;
void JDY09_UART_IRQHandler(void)
{
HAL_UART_IRQHandler(&JDY09_UART);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
uint8_t data = (uint8_t)(huart->Instance->DR & (uint8_t)0x00FF);
JDY09_RX_BUF[JDY09_RX_LEN++] = data;
if (JDY09_RX_LEN >= JDY09_BUF_SIZE)
{
JDY09_RX_LEN = 0;
}
HAL_UART_Receive_IT(&JDY09_UART, &data, 1);
}
void JDY09_Init(void)
{
HAL_UART_Receive_IT(&JDY09_UART, JDY09_RX_BUF, 1);
}
void JDY09_SendString(char *str)
{
HAL_UART_Transmit(&JDY09_UART, (uint8_t *)str, strlen(str), 1000);
}
void JDY09_SendData(uint8_t *data, uint8_t len)
{
HAL_UART_Transmit(&JDY09_UART, data, len, 1000);
}
void JDY09_ProcessData(uint8_t *data, uint8_t len)
{
if (len >= 2 && data[0] == 'A' && data[1] == 'T')
{
JDY09_SendString("OK\r\n");
}
}
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART1_UART_Init();
JDY09_Init();
while (1)
{
if (JDY09_RX_LEN > 0)
{
JDY09_ProcessData(JDY09_RX_BUF, JDY09_RX_LEN);
JDY09_RX_LEN = 0;
}
JDY09_SendString("BT connected\n");
HAL_Delay(1000);
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
/**Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
/**Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK |
RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
/**Configure the Systick interrupt time
*/
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000);
/**Configure the Systick
*/
HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
/* SysTick_IRQn interrupt configuration */
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}
阅读全文