Implement the design on Explorer 16. LED D10 will be used as the RUN LED indicator.
Write an application (in C) which does the following:
1. Make the RUN LED(D10) toggle at every 3.5 Seconds (exact) interval using one of the Timer (Timer 1) module of the Microcontroller.
2. The Knight Rider pattern now consists of 7 LEDs (D9-D3). If the switch (S3) is open, the pattern is from Left to Right direction. If the switch (S3) is closed, the pattern is from Right to Left direction.
3. Repeat the whole process in an infinite way.
Where can I put the 3.5 seconds in the code below?
#define _XTAL_FREQ 8000000 // Specify the oscillator frequency
unsigned int count1 = 200;
unsigned int count2 = 200;
int main(void){
TRISA = 0x00; // Set PORTA as output
TRISDbits.TRISD6 = 1; // Set SW3 input
while(1) {
int i;
int j;
// Toggle RUN LED (D10) every 3.5 seconds using Timer1
LATDbits.LATD0 = !LATDbits.LATD0;
delayFunc();
// Knight Rider pattern from Left to Right direction
for(i = 0; i <= 6; i++) {
LATA = (1 << i);
delayFunc();
}
// Knight Rider pattern: Left to Right or Right to Left depending on SW3 state
if (PORTDbits.RD6 == 0) {
for(j = 7; j >= 0; j--) {
LATA = (1 << j);
delayFunc();
}
} else {
for(j = 0; j <= 7; j++) {
LATA = (1 << j);
delayFunc();
}
}
}
return -1;
}
void delayFunc(void)
{
int j,k;
int a;
for(j = 0; j < count1; j++)
{
for(k=0; k < count2; k++)
{
a = 0;
}
}
}
1 answer
Add the following code snippets to implement the 3.5-second interval:
1. Define the timer interrupt function:
```c
void __interrupt() timer1_ISR(void)
{
if (TMR1IF) {
TMR1IF = 0; // Clear Timer1 interrupt flag
TMR1 = 15536; // Reload Timer1 value for a 3.5 second delay
LATDbits.LATD0 = !LATDbits.LATD0; // Toggle RUN LED (D10)
}
}
```
2. Configure Timer1 and enable its interrupts:
```c
void initTimer1(void)
{
T1CONbits.TMR1CS = 0; // Timer1 clock source is internal clock (Fosc/4)
T1CONbits.T1CKPS = 0b11; // Timer1 prescaler set to 1:8
TMR1 = 15536; // Initial Timer1 value for a 3.5 second delay
T1CONbits.TMR1ON = 1; // Enable Timer1
TMR1IE = 1; // Enable Timer1 interrupt
PEIE = 1; // Enable peripheral interrupts
GIE = 1; // Enable global interrupts
}
```
3. Call the `initTimer1` function before entering the infinite loop in the `main` function:
```c
int main(void)
{
// ...
initTimer1(); // Initialize Timer1 for the 3.5-second interval
while(1)
{
// ...
}
// ...
}
```
These modifications will set up Timer1 to generate a 3.5-second interrupt, which will toggle the RUN LED (D10) on each interrupt.