Crystal oscillators have only one function. That is to provide stable clock pulses to the digital circuit.
Almost all the digital circuits require clock pulses to operate. A microcontroller requires one too. Clock pulses are required for the synchronization of the operations between various peripherals of the MCU. They also provide the timing for the execution of operations.
A clock pulse(CP) is a string of alternating 0’s and 1’s as in the images below
Lets take an example to see the need for CP.
Say your code has only one line to execute
data = 56 – 30;
The following steps are involved in the execution of this line
- Load a memory location with the value 56
- Load another memory location with the value 30
- Perform subtraction
- Store the result in the address of “data” variable
(This is only an overview of the execution. A lot more goes on in to execute this line)
The internal circuitry of MCU contains more of like an AND circuit. Its like
“If you have an operation to perform and the clock pulse transits from positive to negative (or negative to positive), execute it”
CP provides the synchronization for the steps involved. The actions can either happen during a positive edge or a negative edge. Lets say it happens at positive pulse (also called rising edge)
- CP1 – Load a memory location with the value 56
- CP2 – Load another memory location with the value 30
- CP3 – Perform subtraction
- CP4 – Store the result in the address of “data” variable
This also helps in controlling the speed of execution. A higher frequency clock signal will have more number of pulses per second. Hence, faster execution.
Clock Pulses are also needed to keep track of time. Say you need an LED to glow every 1 second. How is the MCU gonna know that 1 second has elapsed and its time to switch on the LED? The clock pulses come to rescue.
If you have a 1MHz crystal attached, you know there will be 1 x 10^6 pulses. So, you keep counting the pulses and once you get 10^6 pulses, you know 1 second has elapsed. (Again this is only an overview. You will have to configure the registers and interrupts)
Wrist watches and analog clocks also use oscillators. It’s the oscillator that helps them keep track of time precisely. Read more about it here: How does a watch keep working at the same pace until the last drop of a battery cell?