stm32串口控制led灯
时间: 2023-06-22 07:46:08 浏览: 121
串口发送点亮led
5星 · 资源好评率100%
好的,下面是控制LED灯的代码,使用STM32的串口通信控制:
```c
#include "stm32f10x.h"
#define LED_PIN GPIO_Pin_13
#define LED_PORT GPIOC
void USART2_IRQHandler(void)
{
if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET)
{
uint16_t ch = USART_ReceiveData(USART2);
if (ch == '1')
{
GPIO_SetBits(LED_PORT, LED_PIN);
}
else if (ch == '0')
{
GPIO_ResetBits(LED_PORT, LED_PIN);
}
}
}
void USART2_Config(void)
{
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
/* Configure USART2 Tx (PA.02) as alternate function push-pull */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Configure USART2 Rx (PA.03) as input floating */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Enable the USART2 Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* USART2 configuration */
USART_InitStructure.USART_BaudRate = 115200;
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(USART2, &USART_InitStructure);
/* Enable USART2 */
USART_Cmd(USART2, ENABLE);
/* Enable USART2 RXNE Interrupt */
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
}
void LED_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Configure PC.13 as push-pull output */
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
}
int main(void)
{
USART2_Config();
LED_Config();
while (1)
{
}
}
```
在这个代码中,我们使用USART2接口来进行串口通信,并通过接收到的字符来控制LED灯的开关。当接收到字符 "1" 时,我们将LED灯打开,当接收到字符 "0" 时,我们将LED灯关闭。
需要注意的是,在使用USART2接口之前,我们需要先初始化USART2和LED的GPIO口。在main函数中我们只需要不停的循环,等待串口中断触发。当触发中断时,我们会读取串口中的一个字符,并根据该字符来控制LED的开关。
阅读全文