Configure USART 2 on STM32F4

I wrote a nice simple piece of code that will configure USART2 on PD5(tx) and PD6(rx). Works like a charm Smile For me so far at least. APBClock is 1/8 my clock… if this doesn’t work its usually a incorrect clock setting.

#define myClock 168000000
#define myBaud 115200

void ConfigUSART2(uint32_t BAUD, uint32_t fosc)
{
uint32_t tmpreg = 0x00, apbclock = 0x00;
uint32_t integerdivider = 0x00;
uint32_t fractionaldivider = 0x00;

apbclock = fosc/8;

RCC->APB1ENR = (1 << 17); //Enable USART2 Clock

GPIOD->MODER |= (2 << 10); //Setup TX pin for Alternate Function
GPIOD->MODER |= (2 << 12); //Setup RX pin for Alternate Function

GPIOD->AFR[0] |= (7 << 20); //Setup TX as the Alternate Function
GPIOD->AFR[0] |= (7 << 24); //Setup RX as the Alternate Function

USART2->CR1 |= (1 << 13); //Enable USART

integerdivider = ((25 * apbclock) / (2 * (BAUD)));
tmpreg = (integerdivider / 100) << 4;
fractionaldivider = integerdivider - (100 * (tmpreg >> 4));

tmpreg |= ((((fractionaldivider * 8) + 50) / 100)) & ((uint8_t)0x07);

USART2->BRR = (uint16_t)tmpreg;
USART2->CR1 |= (3 << 2); //Enable Tx & Rx
}

Advertisements

About atomsoft

Starting a small company. Trying to build it from ground up. Only 2 employees so far. Nothing serious yet but soon!

One response to “Configure USART 2 on STM32F4”

  1. Anonymous Coder says :

    Thank you so much for putting this code here!!! I wasted 14 hours debugging why my TxD & RxD lines were held low when I actiivated the USART using the STM32 Standard Peripheral Library functions. I ran your code using direct register access and the USART worked! After some more debugging, I realized that I had used “GPIO_Pin_5” instead of “GPIO_PinSource5” in the GPIO_PinAFConfig function. I never would have figured it out without your sample code.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: