Code Breakdown:
1. Preprocessor Directives:
#include <pic.h>: Includes the header filepic.h, which contains definitions and declarations specific to PIC microcontrollers.
2. Variable Declarations:
unsigned char count = 0;: Declares an unsigned character variablecountand initializes it to 0. This variable is used to keep track of the number of 50ms intervals that have elapsed.
3. main() Function:
-
Initialization:
TRISC = 0;: Configures PORTC as output pins.PORTC = 0;: Clears the output pins on PORTC.T0CS = 0;: Selects the internal clock source (Fosc/4) for TMR0.PSA = 0;: Assigns the prescaler to TMR0.PS2 = 1; PS1 = 1; PS0 = 1;: Sets the prescaler to 256, providing a timer tick every 50 milliseconds.TMR0 = 61;: Initializes TMR0 with the value 61 to generate a 50ms delay.RC0 = 1;: Sets the output on RC0.
-
Main Loop:
while (1) { ... }: The main loop continues indefinitely.- Interrupt Handling:
if (T0IF) { ... }: Checks if the TMR0 interrupt flag is set.TMR0 = 61;: Reloads TMR0 with the value 61 to start another 50ms delay.count++;: Increments thecountvariable.if (count == 20) { ... }: Checks if 20 50ms intervals have elapsed (1 second).RC0 = !RC0;: Toggles the RC0 output.count = 0;: Resets thecountvariable to 0.
T0IF = 0;: Clears the TMR0 interrupt flag.
Explanation:
The code implements a simple blinking LED circuit that toggles an output pin (RC0) every second. The main components of the code are:
- Timer Initialization: TMR0 is configured as an internal timer with a prescaler of 256, providing a timer tick every 50 milliseconds.
- Interrupt Handling: The TMR0 interrupt is used to increment a counter and toggle the output pin after 20 50ms intervals (1 second).
#include <pic.h>
unsigned char count=0;
unsigned char count=0;
void main()
{
TRISC=0; // PORTC output
PORTC=0;
T0CS=0; // Internal Mode (Fosc/4)
PSA=0; // Prescaler assigned to TMR0
PS2=1;
PS1=1;
PS0=1;
TMR0=61; // (256-195=61) for 50mS time
RC0=1; // output on
while(1)
{
if(T0IF==1){
TMR0=61;
count++;
if (count==20){
RC0=!RC0; // RC0 toggle
count=0;
}
T0IF=0;
}
}
}
{
TRISC=0; // PORTC output
PORTC=0;
T0CS=0; // Internal Mode (Fosc/4)
PSA=0; // Prescaler assigned to TMR0
PS2=1;
PS1=1;
PS0=1;
TMR0=61; // (256-195=61) for 50mS time
RC0=1; // output on
while(1)
{
if(T0IF==1){
TMR0=61;
count++;
if (count==20){
RC0=!RC0; // RC0 toggle
count=0;
}
T0IF=0;
}
}
}
Comments
Post a Comment