dsPIC33A Oscillator Module Deep Dive
Example Project
| Frequency Drift Detection Example | Reference Clocks |
Purpose
This project demonstrates the initialization and usage of the clock monitor to perform a frequency drift detection measurement application using the dsPIC33A Curiosity Platform Board, which features a dsPIC33AK512MPS512 MCU, mounted in the dsPIC33A Curiosity Platform Development Board.
Please review the hardware and software requirements and ensure you have installed a VS Code® development environment on your PC.
Finally, download and extract the dh-dspic33a-osc-clock-monitor-example project to your computer.
Specific Learning Outcomes
- Learn how to configure the clock monitor module for frequency drift detection and measurement
- Learn how firmware triggers and responds to frequency drift alarms
- Apply these techniques to pulse-width and duty-cycle measurements
- Extend these concepts to future dsPIC33A frequency and timing measurement application requirements
Overview
This project configures the monitor clock as a 160 MHz clock generated by CLKGEN11, while the reference clock is the 8 MHz FRC clock generated by CLKGEN2.
To simulate variations in the monitor clock and the resulting frequency drift detection indications, we will vary the reference clock using switches S1, S2 and S3.
Click Play ► to listen to commentary on how the monitor clock frequency drift is simulated in the demo:

Circuit Connections
Click Play ► to listen to commentary on the circuit connections used in the demo:

Clock Monitor Demo Flowchart

Procedure
Open the dsPIC33A Clock Monitor folder.
Within VS Code, go to File > Open Folder, and then locate and select the dsPIC33A Clock Monitor project folder as shown:


Click main.c in the Explorer window to open the file in the editor.
The project files are displayed in the Explorer window.

We encourage you to review all project files to become familiar with the application flow and operation. The clock monitor demo flowchart can assist during this review.
Next, open the clock_monitor.c file, which contains the primary source code for this demo.
The dsPIC33A Oscillator module supports up to four Clock Monitor modules, and this demo uses Clock Monitor 2.
The clock_monitor.c file primarily contains one main function and four Interrupt Service Routines (ISRs) that support the demo application.
| Function | Description |
|---|---|
clock_monitor_init() | clock_monitor_init()
|
void __attribute__((interrupt)) _CM2CNTInterrupt() | Interrupt Handler for expected and normal operations, e.g., the count (resultant frequency) is within an acceptable range. The ISR is generated for every completed normal count window. |
void __attribute__((interrupt)) _CM2WARNInterrupt() | Interrupt Handler when a warning event condition has occurred. Effectively, a failure is generated when CM2BUF crosses CM2HWARN or CM2LWARN threshold values, which the application has pre-configured. |
void __attribute__((interrupt)) _CM2FAILInterrupt() | Interrupt Handler when a failure event condition has occurred. Effectively, a failure is generated when CM2BUF crosses CM2HFAIL or CM2LFAIL threshold values, which the application has pre-configured. |
void __attribute__((interrupt)) _CM2SATInterrupt() | Interrupt Handler for when a count saturation event has occurred. Effectively, a failure is generated when saturation count clamps at CM2SAT. This condition may indicate a reference clock or monitor clock failure. Further investigation would be required. |
To aid in reviewing this demo, refer to the embedded "Frequency Drift Detection Example" image.
Demo Overview
Clock Monitor 2 (CM2) operates in Frequency Measurement mode (signal rising edge to rising edge). CM2 compares a monitored clock against a reference clock and sets status flags when the monitored frequency moves outside expected ranges.
- Key Demo Configuration
- CM2CONbits.WIDTH = 0
→ Frequency Measurement mode - WINPR = 2999
→ Measurement window = 3000 reference clock periods, since the effective count is equal to WINPR + 1.
- CM2CONbits.WIDTH = 0
- Clock Configuration
- Reference Clock = 8 MHz (Internal FRC)
- Monitor Clock = 160 MHz (external 8MHz oscillator + PLL)
- Threshold Registers
- HWT, HFT, LFT, LWT, and SAT define warning, fault, and saturation thresholds
- These thresholds are configured by the application to meet measurement tolerance requirements
Measurement Concept: WINPR defines the measurement window using the reference clock. During this window, the monitor clock runs continuously while CM2 counts monitor clock cycles.
For this demo:
- 8 MHz reference clock period = 125 ns
- 160 MHz monitor clock period = 6.25 ns
This results in:
- 20 monitor clock cycles per reference clock cycle
With a 3000-cycle measurement window:
- 20 × 3000 = 60,000 counts
As a result, CM2BUF captures an expected count value of 60,000. This value is then used to derive the HWT, HFT, LFT, LWT and SAT threshold values used by the demo.
During operation, CM2 continuously compares the captured CM2BUF count against these thresholds to detect frequency drift and/or fault conditions.
Demo Implementation Notes
In a typical application, the reference clock would use a stable, known-good clock source.
To simplify this demo and use only onboard hardware resources:
- The 8 MHz FRC oscillator with tuning capability is used as the reference clock
- The 160 MHz monitor clock is generated from the external 8 MHz oscillator and internal Phase-Locked Loop (PLL)
The demo varies the 8 MHz FRC frequency to simulate:
- A faster reference clock, which can represent a slower monitor clock
- A slower reference clock, which can represent a faster monitor clock

Here are the various thresholds presented in a simple table view.

clock_monitor_init() is called from demo_init(). The function configures CM2 for frequency-drift detection, then blocks until the reference clock is confirmed running.
- Disables CM2 (CM2CONbits.ON = 0) before any configuration write.
- Configures mode and clocks:
- Frequency Measurement mode (WIDTH = 0);
- reference = Clock Generator 2 (8MHz FRC);
- monitored = Clock Generator 11 (160MHz); no pre-scale (CNTDIV = 0).
- Configures the window: CM2WINPR = 2999 → 3000-count window, expected CM2BUF = 60000.
- Configures thresholds (offsets from 60000): LFAIL -1%, LWARN -0.5%, HWARN +0.5%, HFAIL +1%, SAT +1.5%. Two lines to disable a warn threshold exist but stay commented out.
- Clears stale status bits, then configures and enables the four CM2 interrupts (Count, Warn, Fail, Sat).
- Initializes the baseline FRC trim (FRCTUNbits.TUN = 0x3C), and sets the RGB LED to green.
- Enables CM2 (CM2CONbits.ON = 1).
- Runs a startup test: busy-waits on CM2STATbits.TRIG (no timeout) until the reference clock's first edge confirms it is running, then returns.
_CM2CNTInterrupt() is CM2's count ready interrupt handler; it fires once per completed measurement window.
- Opens with a Nop() as a debugger breakpoint anchor
- Checks CM2STATbits.BUFV to confirm CM2BUF holds a valid captured count
- reads CM2BUF into Count_Read,
- computes Freq_Result from that count (Count_Read * 8 MHz / (CM2WINPR + 1)),
- then clears BUFV
- If not valid: falls into an else branch with only a placeholder Nop() — no error handling is implemented, though the comment flags this as an unexpected condition
- Clears _CM2CNTIF at the end, unconditionally, regardless of which branch ran
_CM2WARNInterrupt() is CM2's warning interrupt handler; it fires when CM2BUF crosses CM2LWARN or CM2HWARN.
- Opens with a Nop() as a debugger breakpoint anchor
- Checks CM2STATbits.LWT, then CM2STATbits.HWT (mutually exclusive via else-if). Both branches do the same thing today — a comment notes each could diverge from the other in the future:
- Drives the RGB LED blue (RGB_B_PPS = RGB_PPS_PWM, other two channels off)
- Reads CM2BUF into Count_Read, computes Freq_Result from that count
- Clears its own status bit (LWT or HWT)
- If neither bit is set: falls into an else branch with only a placeholder Nop() — no error handling is implemented, though the comment flags this as an unexpected condition
- Clears _CM2WARNIF at the end, unconditionally
_CM2FAILInterrupt() is CM2's Failure interrupt handler; it fires when CM2BUF crosses CM2LFAIL or CM2HFAIL. A fail event also disables CM2 in hardware.
- Opens with a Nop() as a debugger breakpoint anchor
- Checks CM2STATbits.LFT, then CM2STATbits.HFT (mutually exclusive via else-if). Both branches do the same thing today:
- Drives the RGB LED red (RGB_R_PPS = RGB_PPS_PWM, other two channels off)
- Reads CM2BUF into Count_Read, computes Freq_Result from that count
- Clears its own Fail bit and the matching Warn bit (LFT+LWT, or HFT+HWT) — a comment notes a fail event always crosses its warn threshold too, unless that warn threshold was disabled
- If neither bit is set: falls into an else branch with only a placeholder Nop() — no error handling is implemented, though the comment flags this as an unexpected condition
- Re-enables CM2 (CM2CONbits.ON = 1) unconditionally — a comment warns that if the fault condition has not actually cleared, the handler will re-enter this same ISR as soon as CM2 restarts, so real application code needs to rectify the failure first
_CM2SATInterrupt() is CM2's Saturation interrupt handler; it fires when the count clamps at CM2SAT.\
- Opens with a Nop() as a debugger breakpoint anchor
- Checks CM2STATbits.SATD:
- If set: drives the RGB LED red (RGB_R_PPS = RGB_PPS_PWM, other two channels off), reads CM2BUF into Count_Read, computes Freq_Result from that count — though a comment notes this computation may not be meaningful here, since a saturated CM2BUF no longer reflects the true count. Clears SATD
- If not set: falls into an else branch with only a placeholder Nop() — no error handling is implemented, though the comment flags this as an unexpected condition
Build the project and run it in the debugger.
Use the key combination Ctrl + Shift + B to build the project. If asked to select a build task, select the build task named after your folder and default configuration (in this case, it should be clock_monitor: default - Build)
Upon a successful build, download and start the debugger by pressing F5.
Press the Continue key (again, F5) to run the program on the target.
Alter the reference frequency to exercise the demo application.
At this point, the clock monitor program is running and detecting/measuring any frequency drift.
Follow the instructions on the next two diagrams to increase or decrease the FRC frequency using Switches S1, S2, S3 and the potentiometer R14 setting. In combination with Switch S1 and S3, the various CM2 warning or failure indications on the RGB LED will trigger.
Click Play ► to listen to commentary on how to run the demo and evaluate the RGB LED response:
Clock Monitor Example - Controls


Make sure to press switch S2 twice after each FRC adjustment test to reset the CM2 monitor firmware for the next FRC adjustment. The RGB LED will show green upon pressing switch S2.
Exercise the demo application using breakpoints in VS Code.
You can also set a breakpoint on the Nop(); provided in each of the four ISRs. When the program stops, based on the condition, you can then single-step through the code and view the content of the Watch window variables.
