main.c
#include "stm32f4xx.h" // Device header
#include "serial.h"
#include "delay.h"
#include "OLED.h"
uint16_t ReceiveData;
int main(void)
{
Serial_Init();
printf("123success");
while (1)
{
printf("ReceiveData=%d\r\n",ReceiveData);
Delay_ms(200);
}
}
/*中断用于接收*/
void USART2_IRQHandler(){
if(USART_GetITStatus(USART2,USART_IT_RXNE)==SET){
ReceiveData=USART_ReceiveData(USART2);
USART_ClearITPendingBit(USART2,USART_IT_RXNE);
}
}
Serial.c:
#include "stm32f4xx.h" // Device header
#include <stdio.h>
#include <stdarg.h>
uint8_t Serial_RxData;
uint8_t Serial_RxFlag;
void Serial_Init(void)
{
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
// 使能USART2时钟和GPIOA时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
// 配置PA2引脚为USART2的TX功能
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
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(GPIOA, &GPIO_InitStructure);
// 配置PA3引脚为USART1的RX功能
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 将PA2和PA3引脚连接到USART2的TX和RX功能上
GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2);
// 配置USART1的通信参数
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(USART2, &USART_InitStructure);
USART_ITConfig(USART2,USART_IT_RXNE,ENABLE);
/*接收需要中断*/
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel= USART2_IRQn ;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority= 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority=1 ;
NVIC_Init(&NVIC_InitStructure);
// 使能USART2
USART_Cmd(USART2, ENABLE);
}
int fputc(int ch,FILE *f){
USART_SendData(USART2,ch);
while(USART_GetFlagStatus(USART2,USART_FLAG_TXE)==RESET);
return ch;
}
关联手册...