uart点亮led,用stm32上的c语言来编写这个程序
时间: 2024-05-05 11:17:25 浏览: 65
以下是使用STM32上的C语言编写的UART点亮LED程序:
```
#include "stm32f10x.h"
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
void USART1_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &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(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void LED_Init(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);
}
int main(void)
{
USART1_Init();
LED_Init();
while (1)
{
while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET);
char received_char = USART_ReceiveData(USART1);
if (received_char == '1')
{
GPIO_SetBits(GPIOC, GPIO_Pin_13);
}
else if (received_char == '0')
{
GPIO_ResetBits(GPIOC, GPIO_Pin_13);
}
}
}
```
该程序使用USART1的RX和TX引脚与PC进行通信,当接收到字符'1'时,点亮LED,当接收到字符'0'时,熄灭LED。在程序中,使用GPIO库初始化LED引脚和USART库初始化USART1。在主循环中,使用USART_GetFlagStatus函数检查USART1是否收到了数据。如果收到了,程序将读取接收的字符并根据其值控制LED的状态。
阅读全文