STM32 F411RET6编写一个简单的通信控制程序,发送0x01,控制指示灯亮,发送0x0F,控制指示灯灭。
时间: 2023-06-25 18:03:35 浏览: 57
好的,以下是一个简单的通信控制程序,可以实现您的需求:
```c
#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_usart.h"
#define LED_PIN GPIO_Pin_13
#define LED_GPIO_PORT GPIOG
#define LED_GPIO_CLK RCC_AHB1Periph_GPIOG
#define USARTx USART1
#define USARTx_CLK RCC_APB2Periph_USART1
#define USARTx_TX_PIN GPIO_Pin_9
#define USARTx_TX_GPIO_PORT GPIOA
#define USARTx_TX_GPIO_CLK RCC_AHB1Periph_GPIOA
#define USARTx_RX_PIN GPIO_Pin_10
#define USARTx_RX_GPIO_PORT GPIOA
#define USARTx_RX_GPIO_CLK RCC_AHB1Periph_GPIOA
void USART_Config(void);
void GPIO_Config(void);
void Delay(__IO uint32_t nCount);
int main(void)
{
uint16_t data;
USART_Config();
GPIO_Config();
while (1)
{
while (USART_GetFlagStatus(USARTx, USART_FLAG_RXNE) == RESET)
;
data = USART_ReceiveData(USARTx);
if (data == 0x01)
GPIO_SetBits(LED_GPIO_PORT, LED_PIN);
else if (data == 0x0F)
GPIO_ResetBits(LED_GPIO_PORT, LED_PIN);
}
}
void USART_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_AHB1PeriphClockCmd(USARTx_TX_GPIO_CLK | USARTx_RX_GPIO_CLK, ENABLE);
RCC_APB2PeriphClockCmd(USARTx_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = USARTx_TX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(USARTx_TX_GPIO_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = USARTx_RX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(USARTx_RX_GPIO_PORT, &GPIO_InitStructure);
GPIO_PinAFConfig(USARTx_TX_GPIO_PORT, GPIO_PinSource9, GPIO_AF_USART1);
GPIO_PinAFConfig(USARTx_RX_GPIO_PORT, GPIO_PinSource10, GPIO_AF_USART1);
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(USARTx, &USART_InitStructure);
USART_Cmd(USARTx, ENABLE);
}
void GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(LED_GPIO_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_GPIO_PORT, &GPIO_InitStructure);
}
void Delay(__IO uint32_t nCount)
{
while (nCount--)
;
}
```
上面的程序通过 USART1 接收数据,当接收到 0x01 时,控制 LED 灯亮;当接收到 0x0F 时,控制 LED 灯灭。您需要将 USART1 的 TX 引脚连接到另一个设备,以便向本设备发送数据。此外,还需要将 LED 的正极连接到 PG13 引脚,将负极连接到地。