1 | void initUSART(uint32_t baudrate)
|
2 | {
|
3 | USART_InitTypeDef USART_InitStructure;
|
4 | GPIO_InitTypeDef GPIO_InitStructure;
|
5 | NVIC_InitTypeDef NVIC_InitStructure; // nested vector interrupt controller
|
6 |
|
7 | // Enable clocks
|
8 | RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
|
9 | RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
|
10 |
|
11 | // Prepare required pins to alternative function
|
12 | GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
|
13 | GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
|
14 | GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
|
15 | GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
|
16 | GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
|
17 | GPIO_Init(GPIOA, &GPIO_InitStructure);
|
18 |
|
19 | // Now the pins can be set to alternative function (USART)
|
20 | GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_USART2); // GPIOA PA2: USART2_TX
|
21 | GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_USART2); // GPIOA PA3: USART2_RX
|
22 |
|
23 |
|
24 | // Configuration of USART
|
25 | USART_InitStructure.USART_BaudRate = baudrate;
|
26 | USART_InitStructure.USART_WordLength = USART_WordLength_8b; // standard
|
27 | USART_InitStructure.USART_StopBits = USART_StopBits_1; // standard
|
28 | USART_InitStructure.USART_Parity = USART_Parity_No; // standard
|
29 | USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; // standard
|
30 | USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
|
31 | USART_Init(USART2, &USART_InitStructure);
|
32 |
|
33 |
|
34 | // Configure interrupt handler USART2_IRQHandler()
|
35 | USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
|
36 |
|
37 | NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
|
38 | NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
|
39 | NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
|
40 | NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
|
41 | NVIC_Init(&NVIC_InitStructure);
|
42 |
|
43 |
|
44 | // Enable UART
|
45 | USART_Cmd(USART2, ENABLE);
|
46 | }
|