生成stm32f103串口输出
时间: 2023-11-13 20:04:30 浏览: 67
Protues仿真stm32f103r6输出正弦波
以下是生成stm32f103串口输出的示例代码:
#include "stm32f10x.h"
#include <stdio.h>
// 定义串口输出缓存区大小
#define UART_BUFFER_SIZE 128
// 串口输出缓存区
char uart_buffer[UART_BUFFER_SIZE];
// 重定向printf函数
int fputc(int ch, FILE *f) {
// 将字符加入串口输出缓存区
uart_buffer[strlen(uart_buffer)] = (char)ch;
return ch;
}
int main(void) {
// 初始化串口1
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
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_Cmd(USART1, ENABLE);
// 循环输出
while (1) {
// 输出字符串到串口输出缓存区
sprintf(uart_buffer, "Hello World!\r\n");
// 等待串口发送缓存区为空
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
// 将缓存区的数据发送出去
for (int i = 0; i < strlen(uart_buffer); i++) {
USART_SendData(USART1, uart_buffer[i]);
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
// 清空缓存区
memset(uart_buffer, 0, UART_BUFFER_SIZE);
// 延时一段时间
for (int i = 0; i < 1000000; i++);
}
}
阅读全文