STM32103最小系统用手机蓝牙控制开关灯完整代码
时间: 2024-02-20 10:59:31 浏览: 61
以下是一个基于STM32F103最小系统的蓝牙控制LED灯的完整代码:
```c
#include "stm32f10x.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_rcc.h"
#include "stm32f10x_usart.h"
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
void GPIO_Configuration(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void USART_Configuration(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
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(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void LED_Configuration(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void delay(uint32_t n)
{
uint32_t i;
for (i = 0; i < n; i++);
}
void USART_SendChar(char ch)
{
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
USART_SendData(USART1, ch);
}
char USART_ReceiveChar(void)
{
while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET);
return USART_ReceiveData(USART1);
}
int main(void)
{
char ch;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
GPIO_PinRemapConfig(GPIO_Remap_USART1, ENABLE);
GPIO_Configuration();
USART_Configuration();
LED_Configuration();
while (1)
{
ch = USART_ReceiveChar();
if (ch == '1')
{
GPIO_SetBits(GPIOC, GPIO_Pin_13);
USART_SendChar('L');
}
else if (ch == '0')
{
GPIO_ResetBits(GPIOC, GPIO_Pin_13);
USART_SendChar('H');
}
else
{
USART_SendChar('E');
}
}
}
```
上述代码使用了USART1与蓝牙模块通信,接收蓝牙模块发送的数据后根据数据内容控制LED灯的开关。当接收到字符'1'时,LED灯亮;当接收到字符'0'时,LED灯灭;其他字符则返回'E'表示错误。你可以通过手机蓝牙发送字符'1'或'0',来控制LED灯的开关。
阅读全文