首要界说头文件:
/
RCC_CFGR &= (uint32_t)0xF8FF0000;
RCC_CR &= (uint32_t)0xFEF6FFFF;//
RCC_CR &= (uint32_t)0xFFFBFFFF;//
RCC_CFGR &= (uint32_t)0xFF80FFFF;//
RCC_CIR = 0x00000000;/
RCC_CR |=0x00010000;//
do
{
HSEStatus = RCC_CR & 0x00020000;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != 0x0500));
if ((RCC_CR & 0x00020000) != 0)
{
HSEStatus =0x01;
}
else
{
HSEStatus =0x00;
}
if (HSEStatus ==0x01)
{
RCC_CFGR |=0x00000000;//
RCC_CFGR |=0x00000000;//
RCC_CFGR |=0x00000000;//
RCC_CFGR &=(~(0x00010000 | 0x00020000 | 0x003C0000));
RCC_CFGR |= 0x00010000 | 0x00020000 | 0x000C0000;//
RCC_CR |= 0x01000000;//
while((RCC_CR & 0x02000000) == 0)//
{
}
RCC_CFGR &=~0x00000003;
RCC_CFGR |=0x00000002; //
while ((RCC_CFGR &0x0000000C) !=0x08) //
{
}
}
else
{while (1)
{
}
}
}
设置好时钟就可以串口初始化了:
void stm32_UsartSetup ()//串口初始化
{
RCC_APB2ENR|=0x00004000;// enable clock for USART1
RCC_APB2ENR|=0x00000001;//复用功用IO时钟使能
RCC_APB2ENR|=0x00000004;//端口A时钟使能
GPIO_PORTA_CRH&=~(0x00000FF0);// Clear PA9, PA10
GPIO_PORTA_CRH|=0x000000B0;// USART1 Tx (PA9)alternate output push-pull
GPIO_PORTA_CRH|=0x00000400;// USART1 Rx (PA10) input floating
USART1_BRR=0x00000823;////波特率9600/20M
USART1_CR1&=0xFFFFEFFF;// set Data bits
USART1_CR2&=0xFFFFCFFF;// set Stop bits
USART1_CR1&=0xFFFFFBFF;//// set Parity
USART1_CR1|=(0x00000004|0x00000008);// RX, TX enable
USART1_CR1|=0x00002000;// USART enable
}
到此串口设置设置结束,下面我要和PC机通讯了,我要从上位机经过串口帮手发送一字节的十六进制数,然后下位机(STM32)回来给PC机所发的一字节数据:
int main()
{
SystemInit0();
stm32_UsartSetup ();
while(1)
{
while(USART1->SR&0x00000020)//等候RXNE置位
{
flag=USART1_DR&0xff;
USART1_DR=flag&0xff;
while((USART1->SR)&0x80==0);//等候发送结束
while((USART1->SR)&0x40==0);
flag=USART1->SR;
}
}
}