stm32f103c8t6基于正电原子标准例程-V3.5库函数的UsartPrintf
时间: 2023-08-09 20:08:49 浏览: 96
2,标准例程-V3.5库函数版本.rar
以下是基于正点原子标准例程V3.5库函数的UsartPrintf代码:
首先,在main.c文件中添加以下代码:
```c
#include "stdio.h"
#include "stdarg.h"
#include "string.h"
#include "stm32f10x_usart.h"
#include "usart.h"
#define USARTx USART1
#define USARTx_IRQn USART1_IRQn
void USART1_IRQHandler(void)
{
if(USART_GetITStatus(USARTx, USART_IT_RXNE) != RESET)
{
USART_ClearITPendingBit(USARTx, USART_IT_RXNE);
}
}
int fputc(int ch, FILE *f)
{
USART_SendData(USARTx, (uint8_t)ch);
while(USART_GetFlagStatus(USARTx, USART_FLAG_TXE) == RESET);
return ch;
}
```
然后,在usart.c文件中添加以下代码:
```c
#include "usart.h"
void USART_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB2PeriphClockCmd(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);
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);
USART_Cmd(USART1, ENABLE);
USART_ITConfig(USARTx, USART_IT_RXNE, ENABLE);
}
```
最后,在usart.h文件中添加以下代码:
```c
#ifndef __USART_H
#define __USART_H
#include "stm32f10x.h"
void USART_Configuration(void);
#endif
```
这样,你就可以在程序中使用printf函数进行串口输出了。例如:
```c
#include "stdio.h"
int main()
{
USART_Configuration();
printf("Hello, world!\n");
while(1);
}
```
阅读全文