STM32F107VC/USART

From Teknologisk videncenter
Jump to: navigation, search

Using USART2 on the MCBSTM32C evaluation board

The following example shows minimum configuration of the USART2 using the GPIO port D alternate function.

prerequisite
The FCLK bus runs at 72 MHz. See Clock mode 5
/*****************
USART2 remap: USART2_REMAP = 1 	- section 9.3.8
PD5 = TX
PD6 = RX

PD4 = RTS
PD3 = CTS

CLOCK = PCLK1 AFTER APB1 PRESCALER

BaudRate =   fck / ( 16 * USARTDIV )

Fx: 
  fck = 36 Mhz
  Wanted BuadRate = 9.600

  USARTDIV = fck/ (16 * BaudRate ) =
    36000000/ (16 * 9600) = 234.375

	Mantissa = 234 - as hex = 0xEA
	Fraction = 16*0.375 = 6 - as hex 0x6 



Step  1: RCC_CFGR bits PPRE1[2:0] = 100 -APB1 Prescaler divide by 2 = 36 MHz
Step  2: RCC_APB2ENR - Enable AFIO Clock - Alternate Clock I/O Enable
Step  3: RCC_APB2ENR - Enable Clock for Port D 
Step  4: AFIO_MAPR - Remap USART2 from Port A to Port D
Step  5.1: Enable Port D pin 6 - Floating Input (RX)
Step  5.2: Enable Port D pin 5 - Alternate Function/ Push-Pull Output (TX)
Step  6: RCC_APB1ENR Enable USART2 clock
Step  7.1: USART_BRR bits DIV_Mantissa[11:0] = 0xEA
Step  7.2: USART_BRR bits DIV_fraction[3:0] = 0x6
Step  8: USART_CR1 bit UE - Uart Enable = 1
Step  9: USART_CR1 bit M - Word Length = 0 - 8 bit (Default)
Step 10: USART_CR1 bit WAKE - wake medthod = 0 - Idle Line  (Default)
Step 11: USART_CR1 bit PCE - Parity = 0 Parity disabled (Default)
Step 12: USART_CR1 - all interrupts disabled in tiny mode (Default)
Step 13: USART_CR1 bit TE - Tranmitter enable = 1
Step 14: USART_CR1 bit RE - Receiver enable = 1
This config should be sufficient to use the COM port as basic asynchrounous COM port


*/

void usart_enable( void ) {

//Step  1: RCC_CFGR bits PPRE1[2:0] = 100 -APB1 Prescaler divide by 2 = 36 MHz
rcc_cfgr( 0x00000300, 0 ); //Set PPRE1[1:0] = 0
rcc_cfgr( 0x00000400, 1 ); //Set PPRE1[2] = 1

//Step  2: RCC_APB2ENR - Enable AFIO Clock - Alternate Clock I/O Enable
rcc_apb2enr(1 << 0,ENABLE);

//Step  3: RCC_APB2ENR - Enable Clock for Port D
rcc_apb2enr(1 << 5,ENABLE);

//Step  4: AFIO_MAPR - Remap USART2 from Port A to Port D
rcc_afio_mapr(1 << 3, ENABLE);

//Step 5.1 and 5.2 - Enable pin 6 as RX and pin 5 as TX
GPIOD->CRL &= 0xF00FFFFF;
GPIOD->CRL |= 0x04B00000;			   //Pin 6: 0100 Pin 5: 1011

//Step  6: RCC Enable USART in RCC_APB1ENR
rcc_apb1enr( 1 << 17, ENABLE); //set bit 17 in RCC_APB1ENR (Enable USART2)

//Step  7.1 and 7.2: USART_BRR bits DIV_Mantissa[11:0] = 0xEA and fraction = 6
USART2->BRR = 0x0ea6;

//Step  8: USART_CR1 bit UE - Uart Enable = 1
USART2->CR1 |= 1 << 13;

//Step 13: USART_CR1 bit TE - Tranmitter enable = 1
USART2->CR1 |= 1 << 3;

//Step 14: USART_CR1 bit RE - Receiver enable = 1
USART2->CR1 |= 1 << 2;
}

void usart_tx( char character ) {
	while ((USART2->SR & ( 1 << 6)) == 0) {}; // Wait HSERDY = 1
	USART2->DR = (uint16_t) character;
}

void puts(char *string) {
	int i;
	for ( i=0; string[i] != 0; i++ ) {
		usart_tx(string[i]);
	}
}

Links