#include "stm32f10x.h" #include "oled.h" #include "USART.h" void USART1_IRQHandler(void) { if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) { uint8_t data = USART_ReceiveData(USART1); if (usart_rx_len < USART_RX_BUF_SIZE) { usart_rx_buf[usart_rx_len++] = data; } } } void USART1_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, 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 = 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(USART1, &USART_InitStructure); USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); 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); }
时间: 2024-03-03 07:51:20 浏览: 22
根据您提供的代码,这个问题是由于 `usart_rx_buf` 变量在 `USART.h` 头文件中被定义,然后在 `USART.c` 文件中被实现,但是在 `main.c` 文件中又被定义了一次,导致重复定义了。此外,由于 `usart_rx_buf` 变量在 `USART.h` 头文件中被定义,因此在多个源文件中包含了 `USART.h` 头文件时,也会出现重复定义的问题。
解决这个问题的方法是将 `usart_rx_buf` 变量定义为 `extern`,然后在 `USART.c` 文件中实现它。这样,其他源文件包含了 `USART.h` 头文件后,就不会重复定义 `usart_rx_buf` 变量了。
修改后的 `USART.h` 文件应该像这样:
```c
#ifndef __USART_H
#define __USART_H
#include "stm32f10x.h"
#define USART_RX_BUF_SIZE 256
extern uint8_t usart_rx_buf[USART_RX_BUF_SIZE];
extern uint16_t usart_rx_len;
void USART1_Init(void);
#endif /* __USART_H */
```
修改后的 `USART.c` 文件应该像这样:
```c
#include "USART.h"
uint8_t usart_rx_buf[USART_RX_BUF_SIZE];
uint16_t usart_rx_len = 0;
void USART1_IRQHandler(void)
{
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
uint8_t data = USART_ReceiveData(USART1);
if (usart_rx_len < USART_RX_BUF_SIZE)
{
usart_rx_buf[usart_rx_len++] = data;
}
}
}
void USART1_Init(void)
{
/* 端口初始化 */
/* 串口初始化 */
}
```
修改后的 `main.c` 文件应该像这样:
```c
#include "USART.h"
int main(void)
{
USART1_Init();
while (1) {
// 处理串口接收数据
}
}
```
这样就可以避免 `usart_rx_buf` 变量的重复定义问题了。