2222// 33.4: The AHB clock must be at least 25 MHz when Ethernet is used
2323enum { APB1_PRE = 5 /* AHB clock / 4 */ , APB2_PRE = 4 /* AHB clock / 2 */ };
2424enum { PLL_HSI = 16 , PLL_M = 8 , PLL_N = 180 , PLL_P = 2 }; // Run at 180 Mhz
25- //#define PLL_FREQ PLL_HSI
26- #define PLL_FREQ (PLL_HSI * PLL_N / PLL_M / PLL_P)
2725#define FLASH_LATENCY 5
28- #define FREQ (PLL_FREQ * 1000000)
26+ #define SYS_FREQUENCY ((PLL_HSI * PLL_N / PLL_M / PLL_P) * 1000000)
27+ #define APB2_FREQUENCY (SYS_FREQUENCY / (BIT(APB2_PRE - 3)))
28+ #define APB1_FREQUENCY (SYS_FREQUENCY / (BIT(APB1_PRE - 3)))
2929
3030static inline void spin (volatile uint32_t count ) {
3131 while (count -- ) asm("nop" );
@@ -86,10 +86,11 @@ static inline void uart_init(USART_TypeDef *uart, unsigned long baud) {
8686 // https://www.st.com/resource/en/datasheet/stm32f429zi.pdf
8787 uint8_t af = 7 ; // Alternate function
8888 uint16_t rx = 0 , tx = 0 ; // pins
89+ uint32_t freq = 0 ; // Bus frequency. UART1 is on APB2, rest on APB1
8990
90- if (uart == UART1 ) RCC -> APB2ENR |= BIT (4 );
91- if (uart == UART2 ) RCC -> APB1ENR |= BIT (17 );
92- if (uart == UART3 ) RCC -> APB1ENR |= BIT (18 );
91+ if (uart == UART1 ) freq = APB2_FREQUENCY , RCC -> APB2ENR |= BIT (4 );
92+ if (uart == UART2 ) freq = APB1_FREQUENCY , RCC -> APB1ENR |= BIT (17 );
93+ if (uart == UART3 ) freq = APB1_FREQUENCY , RCC -> APB1ENR |= BIT (18 );
9394
9495 if (uart == UART1 ) tx = PIN ('A' , 9 ), rx = PIN ('A' , 10 );
9596 if (uart == UART2 ) tx = PIN ('A' , 2 ), rx = PIN ('A' , 3 );
@@ -100,7 +101,7 @@ static inline void uart_init(USART_TypeDef *uart, unsigned long baud) {
100101 gpio_set_mode (rx , GPIO_MODE_AF );
101102 gpio_set_af (rx , af );
102103 uart -> CR1 = 0 ; // Disable this UART
103- uart -> BRR = FREQ / APB2_PRE / baud ; // FREQ is a CPU frequency
104+ uart -> BRR = freq / baud ; // Set baud rate
104105 uart -> CR1 |= BIT (13 ) | BIT (2 ) | BIT (3 ); // Set UE, RE, TE
105106}
106107
0 commit comments