stm32f103c8t6蓝牙HC05控制LED代码
时间: 2023-07-31 21:13:31 浏览: 94
好的,以下是一个简单的示例代码,可以通过蓝牙模块HC05控制STM32F103C8T6上的LED灯:
```c
#include "stm32f10x.h"
#include <string.h>
#define LED_PIN GPIO_Pin_12
#define LED_PORT GPIOB
#define USART_RX_PIN GPIO_Pin_11
#define USART_TX_PIN GPIO_Pin_10
#define USART_GPIO GPIOA
#define USART USART1
#define USART_IRQn USART1_IRQn
void GPIO_Configuration(void);
void USART_Configuration(void);
void NVIC_Configuration(void);
void delay_ms(uint32_t ms);
int main(void)
{
char buf[10];
uint8_t len = 0;
GPIO_Configuration();
USART_Configuration();
NVIC_Configuration();
while (1) {
if (USART_GetFlagStatus(USART, USART_FLAG_RXNE)) {
buf[len++] = USART_ReceiveData(USART);
if (buf[len - 1] == '\n') {
buf[len - 1] = '\0';
len = 0;
if (strcmp(buf, "on") == 0) {
GPIO_WriteBit(LED_PORT, LED_PIN, Bit_SET);
} else if (strcmp(buf, "off") == 0) {
GPIO_WriteBit(LED_PORT, LED_PIN, Bit_RESET);
}
}
}
}
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
}
void USART_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = USART_TX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(USART_GPIO, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = USART_RX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(USART_GPIO, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART, &USART_InitStructure);
USART_Cmd(USART, ENABLE);
}
void NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_ITConfig(USART, USART_IT_RXNE, ENABLE);
}
void USART1_IRQHandler(void)
{
if (USART_GetFlagStatus(USART, USART_FLAG_RXNE) == SET) {
USART_ClearFlag(USART, USART_FLAG_RXNE);
}
}
void delay_ms(uint32_t ms)
{
uint32_t i, j;
for (i = 0; i < ms; i++) {
for (j = 0; j < 7200; j++);
}
}
```
在这个示例代码中,我们通过USART1接口来接收蓝牙模块发送的数据。当收到一行数据时,我们将其解析,根据指令控制LED灯的开关状态。
需要注意的是,这个示例代码中只是简单的实现了控制LED灯开关的功能,如果你需要更加复杂的功能,还需要根据实际情况进行修改和扩展。
阅读全文