@@ -11,12 +11,54 @@ import (
1111
1212const deviceName = esp .Device
1313
14- const peripheralClock = 40_000000 // 80MHz
14+ const xtalClock = 40_000000 // 40MHz
15+ const apbClock = 80_000000 // 80MHz
16+ const cryptoPWMClock = 160_000000 // 160MHz
17+
18+ // GetCPUFrequency returns the current CPU frequency of the chip.
19+ func GetCPUFrequency () (uint32 , error ) {
20+ switch esp .SYSTEM .GetSYSCLK_CONF_SOC_CLK_SEL () {
21+ case 0 :
22+ return xtalClock / (esp .SYSTEM .GetSYSCLK_CONF_PRE_DIV_CNT () + 1 ), nil
23+ case 1 :
24+ switch esp .SYSTEM .GetCPU_PER_CONF_CPUPERIOD_SEL () {
25+ case 0 :
26+ return 80e6 , nil
27+ case 1 :
28+ return 160e6 , nil
29+ case 2 :
30+ // If esp.SYSTEM.GetCPU_PER_CONF_PLL_FREQ_SEL() == 1, this is undefined
31+ return 240e6 , nil
32+ }
33+ case 2 :
34+ //RC Fast Clock
35+ return (175e5 ) / (esp .SYSTEM .GetSYSCLK_CONF_PRE_DIV_CNT () + 1 ), nil
36+ }
37+ return 0 , errors .New ("machine: Unable to determine current cpu frequency" )
38+ }
1539
16- // CPUFrequency returns the current CPU frequency of the chip.
17- // Currently it is a fixed frequency but it may allow changing in the future.
18- func CPUFrequency () uint32 {
19- return 160e6 // 80 MHz
40+ // SetCPUFrequency sets the frequency of the CPU to one of several targets
41+ func SetCPUFrequency (frequency uint32 ) error {
42+ // Always assume we are on PLL. Lower frequencies can be set with a different
43+ // clock source, but this will change the behavior of APB clock and Crypto PWM
44+ // clock
45+ //esp.SYSTEM.SetSYSCLK_CONF_SOC_CLK_SEL(1)
46+
47+ switch frequency {
48+ case 80_000000 :
49+ esp .SYSTEM .SetCPU_PER_CONF_CPUPERIOD_SEL (0 )
50+ esp .SYSTEM .SetCPU_PER_CONF_PLL_FREQ_SEL (0 ) // Reduce PLL freq when possible
51+ return nil
52+ case 160_000000 :
53+ esp .SYSTEM .SetCPU_PER_CONF_CPUPERIOD_SEL (1 )
54+ esp .SYSTEM .SetCPU_PER_CONF_PLL_FREQ_SEL (0 )
55+ return nil
56+ case 240_000000 :
57+ esp .SYSTEM .SetCPU_PER_CONF_PLL_FREQ_SEL (1 ) // Increase PLL freq when needed
58+ esp .SYSTEM .SetCPU_PER_CONF_CPUPERIOD_SEL (2 )
59+ return nil
60+ }
61+ return errors .New ("machine: Unsupported CPU frequency selected. Supported: 80, 160, 240 MHz" )
2062}
2163
2264var (
@@ -188,7 +230,8 @@ func (uart *UART) Configure(config UARTConfig) {
188230 if config .BaudRate == 0 {
189231 config .BaudRate = 115200
190232 }
191- uart .Bus .CLKDIV .Set (peripheralClock / config .BaudRate )
233+ // Crystal clock source is selected by default
234+ uart .Bus .CLKDIV .Set (xtalClock / config .BaudRate )
192235}
193236
194237func (uart * UART ) writeByte (b byte ) error {
0 commit comments