发上STM32的串口程序,供大家学习
usart1.c
在程序调试的时候,用printf来打印程序中的变量,监测程序的运行很不错
/****************************************************************
程 序 名:stm32_usart1.c
作 者:liu_xf
版 本 号:V1.00
建立日期:
修改日期:
编译环境:
硬件平台:
功能描述:
***************************************************************/
#include "com.h"
#include "usart1.h"
#include "stdio.h"
/********************************************************************
函数功能:串口1初始化
入口参数:无
返 回:无。
备 注:
********************************************************************/
void Usart1_Init(void)
{
u32 USART_BaudRate=9600; //要设定的波特率
u32 PCLK2_Freq=72000000; //PCLK2的频率
u32 tmpreg = 0x00;
u32 integerdivider = 0x00;
u32 fractionaldivider = 0x00;
//打开USART1时钟 ------------------------------------
RCC->APB2ENR.B.USART1EN=1;
//IO配制----------------------------------------
//Configure USART1 Tx (PA.09) as alternate function push-pull
GPIOA->CRH.B.MODE9 = 2; //2M
GPIOA->CRH.B.CNF9 = 2; //复用推挽输出
//Configure USART1 Rx (PA.10) as input floating
GPIOA->CRH.B.MODE10 = 0; //输入
GPIOA->CRH.B.CNF10 = 1; //浮空
//end------------------------------------------------
//串口配制 -------------------------------------
USART1->CR2.B.STOP=0; //1位停止位
USART1->CR1.B.M=0; //1个超始位,8个数据位
USART1->CR1.B.PS=0; //偶校验
USART1->CR1.B.TE=1; //发送使能
USART1->CR1.B.RE=1; //接收使能
USART1->CR3.B.RTSE=0; //RTS硬件流控制被禁止
USART1->CR3.B.CTSE=0; //CTS硬件流控制被禁止
//波特率设置
//Determine the integer part
integerdivider = ((0x19 * PCLK2_Freq) / (0x04 * (USART_BaudRate)));
tmpreg = (integerdivider / 0x64) << 0x04;
//Determine the fractional part
fractionaldivider = integerdivider - (0x64 * (tmpreg >> 0x04));
tmpreg |= ((((fractionaldivider * 0x10) + 0x32) / 0x64)) & ((u8)0x0F);
// Write to USART BRR
USART1->BRR.W = (u16)tmpreg;
//end-------------------------------------------
USART1->CR1.B.UE =1 ; //USART1模块使能
printf("\r\n Usart1 OK! \r\n");
}
/*******************************************************************************
* Function Name : fputc
* Description : Retargets the C library printf function to the USART.
* Input : None
* Output : None
* Return : None
***************************************************************************** **/
int fputc(int ch, FILE *f)
{
// Place your implementation of fputc here
//e.g. write a character to the USART
USART1->DR.W = ((u16)ch & (u16)0x01FF);
///Loop until the end of transmission
while(USART1->SR.B.TC==0); //等待发送完成
return ch;
}
/********************************************************************
函数功能:串口1发送数据
入口参数:DatBuf:要发送的数据缓存区。 len:要发送的数据长度
返 回:无。
备 注:
********************************************************************/
void Usart1_SendData(u8 *DatBuf, u32 len)
{
u32 i;
for(i=0;i<len;i++)
{
while(USART1->SR.B.TC==0); //等待发送完成
USART1->DR.W = ((u16)DatBuf[i] & (u16)0x01FF);
}
}
|