A clock is the core component of a microcontroller, acting like a heartbeat that synchronizes all internal circuits. Imagine it as the rhythm in a radio broadcast during morning exercises, where everyone moves in sync with the beat—like "1234, 2234, 3234..." The faster the beat, the quicker the movement; the slower the beat, the more relaxed the pace.
What’s the difference between an internal and external clock?
Many PIC microcontrollers allow you to choose between an internal RC oscillator or an external clock source, such as a 4MHz crystal. Some models even support multiple clock frequencies. For example, the PIC18LF1823 can operate at up to 32MHz internally or as low as 31kHz. This flexibility is especially useful for power-saving applications. While sleep modes are common for reducing power, sometimes you still need the CPU to run. Lowering the clock frequency is a great alternative to save power without stopping the processor completely.
How do you configure the clock?
Generally, clock settings are controlled by two main components: the configuration word and the OSCCON register. Let's take the PIC18LF1823 as an example.
The configuration word includes bits like FOSC<2:0> (oscillator selection) and PLLEN (PLL enable). The OSCCON register is used to set the internal clock frequency. If you're using an external clock, this register is usually not needed.
Here's a detailed look at the OSCCON register from the datasheet:
Example explanation:
Let’s set the clock frequency to 8MHz using the internal oscillator.
Development environment: MPLAB X IDE
Chip model: PIC18LF1823
#include <xc.h>
__CONFIG(FOSC_INTOSC & WDTE_OFF & PWRTE_ON & MCLRE_OFF & CP_ON & CPD_OFF & BOREN_ON & CLKOUTEN_OFF & IESO_ON & FCMEN_ON);
__CONFIG(PLLEN_OFF & LVP_OFF); // Set FOSC<2:0> to INTOSC
void init_fosc(void)
{
OSCCON = 0x70; // Set internal clock to 8MHz
}
int main(int argc, char** argv)
{
init_fosc();
while(1);
}
What is the purpose of the PLL? It multiplies the input frequency by four. So, if you have an 8MHz clock, the PLL can boost it to 32MHz. However, it only works with specific input frequencies, like 8MHz, not others.
Now, let's set the clock to 32MHz using the internal oscillator.
Development environment: MPLAB X IDE
Chip model: PIC18LF1823
#include <xc.h>
__CONFIG(FOSC_INTOSC & WDTE_OFF & PWRTE_ON & MCLRE_OFF & CP_ON & CPD_OFF & BOREN_ON & CLKOUTEN_OFF & IESO_ON & FCMEN_ON);
__CONFIG(PLLEN_ON & LVP_OFF); // Enable PLL and set FOSC<2:0> to INTOSC
void init_fosc(void)
{
OSCCON = 0xF0; // Set internal clock to 8MHz and enable 4X PLL
}
int main(int argc, char** argv)
{
init_fosc();
while(1);
}
Ceramic Guides For Sale,Al2O3 Ceramic Guides,Custom Ceramic Guides,Ceramic Guides Rod
Yixing Guangming Special Ceramics Co.,Ltd , https://www.yxgmtc.com