#include <stdio.h>
#include "main.h"
void RCC_Configuration(void);
void GPIO_Configuration(void);
void NVIC_Configuration(void);
void USART_Configuration(void);
void RCC_Configuration(void)
{
/* Enable GPIO clock */
RCC_EnableAPB2PeriphClk( USARTz_GPIO_CLK | RCC_APB2_PERIPH_AFIO, ENABLE);
/* Enable USARTy and USARTz Clock */
USARTz_APBxClkCmd(USARTz_CLK, ENABLE);
}
void GPIO_Configuration(void)
{
GPIO_InitType GPIO_InitStructure;
/* Configure USARTy Rx as input floating */
GPIO_InitStructure.Pin = USARTz_RxPin;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitPeripheral(USARTz_GPIO, &GPIO_InitStructure);
/* Configure USARTy Tx as alternate function push-pull */
GPIO_InitStructure.Pin = USARTz_TxPin;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitPeripheral(USARTz_GPIO, &GPIO_InitStructure);
}
/*
void NVIC_Configuration(void)
{
NVIC_InitType NVIC_InitStructure;
//Configure the NVIC Preemption Priority Bits
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
// Enable the USARTz Interrupt
NVIC_InitStructure.NVIC_IRQChannel = USARTz_IRQn;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
*/
void USART_Configuration(void)
{
USART_InitType USART_InitStructure;
USART_InitStructure.BaudRate = 9600;//波特率配置
USART_InitStructure.WordLength = USART_WL_8B;//八个字节
USART_InitStructure.StopBits = USART_STPB_1;//一个停止位
USART_InitStructure.Parity = USART_PE_NO;//无奇偶校验
USART_InitStructure.HardwareFlowControl = USART_HFCTRL_NONE;//控制硬件流控模式,用于MCU通知模块,或者模块通知MCU
USART_InitStructure.Mode = USART_MODE_RX | USART_MODE_TX;//同时开启发送和接收
/* Configur USARTz */
USART_Init(USARTz, &USART_InitStructure);
/* Enable USARTz Receive and Transmit interrupts
USART_ConfigInt(USARTz, USART_INT_RXDNE, ENABLE);
USART_ConfigInt(USARTz, USART_INT_TXDE, ENABLE);*/
/* Enable USARTz */
USART_Enable(USARTz, ENABLE);
}
int main(void)
{
/* System Clocks Configuration */
RCC_Configuration();
/* NVIC configuration
NVIC_Configuration();*/
/* Configure the GPIO ports */
GPIO_Configuration();
/* USARTz configuration ------------------------------------------------------*/
USART_Configuration();
// 主循环,等待接收数据并返回信息给电脑端
while (1)
{
if (USART_GetFlagStatus(USART2,USART_INT_RXDNE) == SET) // 检查是否收到数据
{
int a = USART_ReceiveData(USART2); //读取接收到的数据
// 创建一个足够大的缓冲区来存储转换后的字符串
// 将整数a转换为字符串并存储在buffer中 sprintf(buffer, "%d", a);
printf("%d\n",a); // 把收到的数据发送回电脑
while (USART_GetFlagStatus(USART2,USART_INT_RXDNE) == RESET); // 等待发送完成
}
}
}