举一个使用单片机stm32f103c8t6用USART_SendData利用串口向外发送八位数字的程序例子
时间: 2023-03-03 17:26:58 浏览: 71
以下是一个使用单片机stm32f103c8t6通过串口向外发送八位数字的例子程序:
```c
#include "stm32f10x.h"
void USART1_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStruct;
// 使能USART1和GPIOA时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
// 配置PA9作为USART1的Tx引脚
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStruct);
// 配置USART1
USART_InitStruct.USART_BaudRate = 9600;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx;
USART_Init(USART1, &USART_InitStruct);
// 使能USART1
USART_Cmd(USART1, ENABLE);
}
void USART1_Send8bitData(uint8_t data)
{
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
USART_SendData(USART1, data);
}
int main(void)
{
// 初始化USART1
USART1_Init();
// 发送八位数字
uint8_t data = 123;
USART1_Send8bitData(data);
while(1);
}
```
在这个例子程序中,我们首先定义了一个函数`USART1_Init()`,用于初始化USART1。在该函数中,我们首先使能了USART1和GPIOA的时钟,并配置了PA9作为USART1的Tx引脚。然后,我们配置了USART1的参数,如波特率、数据位、停止位和校验位等,并使能了USART1。接着,我们定义了一个函数`USART1_Send8bitData()`,用于向外发送一个八位数字。在该函数中,我们使用`USART_SendData()`函数将数据发送出去。最后,在`main()`函数中,我们调用`USART1_Send8bitData()`函数并传入一个八位数字,将该数字通过USART1发送出去。