UART串口实现流水灯代码
时间: 2023-10-26 16:24:01 浏览: 85
好的,以下给出一个基于STM32单片机的UART串口实现流水灯的代码示例,供你参考:
```c
#include "stm32f10x.h"
#define LED_Pin GPIO_Pin_13
#define LED_Port GPIOC
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
void USART1_IRQHandler(void) {
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) {
uint16_t data = USART_ReceiveData(USART1);
if (data == '1') {
GPIO_SetBits(LED_Port, LED_Pin);
} else if (data == '0') {
GPIO_ResetBits(LED_Port, LED_Pin);
}
}
}
void USART_Config(void) {
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
// USART1_TX -> PA9, USART1_RX -> PA10
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);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_Cmd(USART1, ENABLE);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
}
void LED_Config(void) {
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, 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);
}
int main(void) {
USART_Config();
LED_Config();
while (1) {
// 这里可以添加其他的代码逻辑
}
}
```
这段代码中,我们首先定义了串口和LED所在的引脚,然后在USART_Config()函数中初始化了USART1串口,设置了波特率为9600,并开启了接收中断。在USART1_IRQHandler()中,我们判断接收到的数据是'1'还是'0',如果是'1'则点亮LED,如果是'0'则熄灭LED。
在主函数中,我们调用了USART_Config()和LED_Config()函数进行初始化,并在while循环中可以添加其他的代码逻辑。需要注意的是,这里的代码是基于STM32单片机的,如果你使用的是其他的单片机或者开发板,代码实现方式可能会有所不同。