如何在keil5的环境下编写stm32的串口通讯代码,请编写它的.c文件与.h文件
时间: 2023-03-20 08:02:36 浏览: 109
下面是一个简单的示例,展示如何在Keil5环境下编写基本的STM32串口通讯代码。这里使用的是STM32F4系列的芯片,但是代码可以根据不同的芯片进行修改。
### .h文件
```c
#ifndef __USART_H
#define __USART_H
#include "stm32f4xx.h"
#include <stdio.h>
#define USARTx USART2
#define USARTx_CLK RCC_APB1Periph_USART2
#define USARTx_CLK_INIT RCC_APB1PeriphClockCmd
#define USARTx_IRQn USART2_IRQn
#define USARTx_IRQHandler USART2_IRQHandler
#define USARTx_TX_PIN GPIO_Pin_2
#define USARTx_TX_GPIO_PORT GPIOD
#define USARTx_TX_GPIO_CLK RCC_AHB1Periph_GPIOD
#define USARTx_TX_SOURCE GPIO_PinSource2
#define USARTx_TX_AF GPIO_AF_USART2
#define USARTx_RX_PIN GPIO_Pin_3
#define USARTx_RX_GPIO_PORT GPIOD
#define USARTx_RX_GPIO_CLK RCC_AHB1Periph_GPIOD
#define USARTx_RX_SOURCE GPIO_PinSource3
#define USARTx_RX_AF GPIO_AF_USART2
#define USARTx_BAUDRATE 115200
void USART_Config(void);
void USART_SendChar(char data);
void USART_SendString(char *string);
int fputc(int ch, FILE *f);
#endif /* __USART_H */
```
### .c文件
```c
#include "usart.h"
void USART_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* Enable GPIO clock */
RCC_AHB1PeriphClockCmd(USARTx_TX_GPIO_CLK | USARTx_RX_GPIO_CLK, ENABLE);
/* Enable USART clock */
USARTx_CLK_INIT(USARTx_CLK, ENABLE);
/* Connect USART pins to AF7 */
GPIO_PinAFConfig(USARTx_TX_GPIO_PORT, USARTx_TX_SOURCE, USARTx_TX_AF);
GPIO_PinAFConfig(USARTx_RX_GPIO_PORT, USARTx_RX_SOURCE, USARTx_RX_AF);
/* Configure USART TX and RX pins */
GPIO_InitStructure.GPIO_Pin = USARTx_TX_PIN | USARTx_RX_PIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOD, &GPIO_InitStructure);
/* Configure USART */
USART_InitStructure.USART_BaudRate = USARTx_BAUDRATE;
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_Tx | USART_Mode_Rx;
USART_Init(USARTx, &USART_InitStructure);
/* Enable USART */
USART_Cmd(USARTx, ENABLE);
/* Configure USART interrupt */
USART_ITConfig(USARTx, USART_IT_RXNE, ENABLE);
/* Enable the USARTx Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USARTx_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void USART_SendChar(char data)
{
while (USART_GetFlagStatus(USART
阅读全文