Step 4: Add Application Code to the Project
Add Application Code to the Project
Once the project is generated, open the main.c file and add the following code outside the while loop (inside int main(void)).
Add the following code inside the while loop (inside int main(void)).
{
LED1_Toggle();
}
TC0_TimerStart() starts the TC0 timer. It begins counting based on its configuration (prescaler time period, etc.).
Inside the while loop, the code checks if the timer period has expired using TC0_TimerPeriodHasExpired(). If this function returns true, it means the timer has completed its set period. When this happens, LED1_Toggle() is called to toggle the state of LED1 (turn it ON if it was OFF, or OFF if it was ON).
The TC0_TimerPeriodHasExpired() function checks if the TC0 timer has overflowed (period expired). If so, it clears the overflow flag and returns true. If not, it returns false.
The TC0_TimerPeriodHasExpired() function is present in the plib_tc0.c file, which is located under Lab5_demo > Source Files > config > default > peripheral > tc > plib_tc0.c.

In this function, timer_status = (uint8_t)((TC0_REGS->COUNT16.TC_INTFLAG) & TC_INTFLAG_OVF_Msk) reads the interrupt flag register (TC_INTFLAG) of the 16-bit timer (COUNT16) in TC0. It performs a bitwise AND with TC_INTFLAG_OVF_Msk, which is a mask for the overflow flag (OVF).
- If the overflow flag is set, timer_status will be non-zero.
- If not set, timer_status will be zero.
TC0_REGS->COUNT16.TC_INTFLAG = timer_status writes the value of timer_status back to the interrupt flag register. In most microcontroller timer peripherals, writing a '1' to the overflow flag bit clears it. This means the function not only checks the flag but also clears it, so the next overflow can be detected.
Then this function returns true if timer_status is not zero; otherwise, it returns false.
The following diagram illustrates the operation of the TC0 timer in normal counting mode. The timer counter increments linearly from 0 with each clock tick until it reaches the predefined TOP value. When the TOP value is reached, an overflow (OVF) event occurs, the counter resets to 0, and the counting process repeats. Each rising ramp represents one timer counting cycle, and the time between two consecutive overflows defines the timer period.
