stm32f103 串口发送 代码
时间: 2023-09-19 20:08:31 浏览: 92
下面是一个基本的 STM32F103 串口发送代码:
```c
#include "stm32f10x.h"
#include <stdio.h>
void USART1_Init(void);
void USART1_SendChar(char ch);
void USART1_SendString(char* str);
int main(void) {
USART1_Init();
USART1_SendString("Hello World!\r\n");
while(1) {}
}
void USART1_Init(void) {
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
// Enable clock for GPIOA and USART1
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_USART1, ENABLE);
// Configure USART1 Tx (PA9) as alternate function push-pull
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);
// Configure USART1 Rx (PA10) as input floating
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// Configure 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(USART1, &USART_InitStructure);
// Enable USART1
USART_Cmd(USART1, ENABLE);
}
void USART1_SendChar(char ch) {
// Wait until transmit data register is empty
while(!(USART1->SR & USART_SR_TXE));
// Send character
USART1->DR = (ch & 0xFF);
}
void USART1_SendString(char* str) {
// Send characters until null terminator is reached
while(*str) {
USART1_SendChar(*str++);
}
}
```
这个代码初始化了 USART1 串口,并发送了 "Hello World!" 到电脑。串口的波特率是 9600,8 位数据位,1 个停止位,无校验。在 `main` 函数中调用 `USART1_Init` 函数初始化串口,调用 `USART1_SendString` 函数发送字符串。 `USART1_SendChar` 函数用于发送单个字符。
阅读全文