帮我写stm32f103c8t6最小系统板uart1串口通信
时间: 2023-09-01 20:13:02 浏览: 229
好的,下面是stm32f103c8t6最小系统板uart1串口通信的代码。
```c
#include "stm32f10x.h"
void USART1_Init(void);
void USART1_SendChar(uint8_t ch);
void USART1_SendString(uint8_t* str);
int main(void)
{
USART1_Init();
USART1_SendString("Hello, world!\r\n");
while(1)
{
// do something
}
}
void USART1_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
// 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);
// 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);
// USART1 initialization
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_Tx | USART_Mode_Rx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void USART1_SendChar(uint8_t ch)
{
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
USART_SendData(USART1, ch);
while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);
}
void USART1_SendString(uint8_t* str)
{
while (*str)
{
USART1_SendChar(*str++);
}
}
```
该代码使用了stm32f10x库,需要在工程中添加相关文件并进行配置。其中,USART1_Init()函数用来初始化串口1,USART1_SendChar()函数用来发送单个字符,USART1_SendString()函数用来发送字符串。在main()函数中,先初始化串口1,然后发送一个“Hello, world!”字符串,最后进入死循环。
阅读全文