一、基本资料
- 快速编写:6-STM32固件库代码V3.5版\stm32f10x_stdperiph_lib\STM32F10x_StdPeriph_Lib_V3.5.0\Project\STM32F10x_StdPeriph_Examples\USART\ Interrupt
- 我们能够看到他有两个串口,一个是串口1(PA9,PA10),一个是串口2(PA2,PA3),TX为发送端,RX为接收端。不过,我们的蓝桥杯嵌入式开发板并不能直接使用串口1,虽然确实有串口1的电路,但是它连接的确实RS232的9针串口上,也就是说,我们不能直接通过USB去使用到这串口,因此我们一般都用不了这个串口。那么我们一般使用的串口就是串口2了,我们可以直接通过usb下载线去使用这个串口。
二、主要代码
usart.c
#include "usart.h"
void USART2_Init(unsigned long Baud)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
/* Configure USARTy Rx as input floating */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Configure USARTz Tx as alternate function push-pull */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_InitStructure.USART_BaudRate = Baud;
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);
USART_Cmd(USART2, ENABLE);
}
unsigned char USART_SendChar(USART_TypeDef* USARTx,unsigned char ucChar)
{
while(!USART_GetFlagStatus(USART2,USART_FLAG_TXE));
USART_SendData(USARTx,ucChar);
return ucChar;
}
void USART_SendString(USART_TypeDef* USARTx,unsigned char*pucStr)
{
while(*pucStr != '\0')
USART_SendChar(USARTx,*pucStr++);
}
int fputc(int ch, FILE *f) //为了调用printf函数 记得开MicroLib
{
return USART_SendChar(USART2,ch);
}
usart.h
#ifndef __LED_H_
#define __LED_H_
#include "stm32f10x.h"
#include "stdio.h"
void USART_SendString(USART_TypeDef* USARTx,unsigned char*pucStr);
unsigned char USART_SendChar(USART_TypeDef* USARTx,unsigned char ucChar);
void USART2_Init(unsigned long Baud);
#endif
main.c中所加中断代码
void USART2_IRQHandler(void)
{
if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET)
{
USART_ClearITPendingBit(USART2,USART_IT_RXNE);
temp = USART_ReceiveData(USART2);
// if(temp == '\n')
// {
// RxBuffer1[RxCounter1-1] = 0; //避免\r显示在LCD发生乱码
// RxCounter1 = 0; //计数清零
// Rxdover = 1;
// USART_ITConfig(USART2, USART_IT_RXNE, DISABLE);
// }
// else
// {
// RxBuffer1[RxCounter1++] = USART_ReceiveData(USART2);
// }
}
}
三、文献参考
1.Zach_z作者代码
2.fei…作者代码