Implement the design on Explorer 16 as Project 1. LED D10 will be used as the RUN LED indicator.
Knight rider code:
unsigned int count1 = 200;
unsigned int count2 = 200;
void main(void) {
TRISA = 0x00;
LATA = 0x00;
while(1) {
int i;
int j;
// Right to Left sequence
for(i=0; i<8; i++) {
LATA |= (1 << i);
delayFunc();
}
// Left to Right sequence
for(j=7; j>=-1; j--) {
LATA |= (1<<j);
delayFunc();
}
// Left to Right sequence if SW3 is pressed
if(PORTDbits.RD6 == 0) {
LATA = 0x00;
for(j=8; j>=-1; 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;
}
}
}
Using the knight rider code above, do the following:
Write an simple application (in C) which does the following:
1. Make the RUN LED(D10) toggle at every 1.45 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.
4. To toggle the RUN LED, precisely at 1.45 Seconds interval, you need to use the interrupt mechanism for the Timer1.
Can you make very simple code, please?
1 answer
```c
#define _XTAL_FREQ 16000000 // Oscillator frequency
#include <xc.h>
// Function prototypes
void interrupt ISR();
void delayFunc();
unsigned int count1 = 200;
unsigned int count2 = 200;
unsigned char pattern = 0x18;
unsigned char direction = 1;
void main(void) {
TRISA = 0xFF; // Set PORTA as output
LATA = 0x00; // Initialize PORTA as LOW
INTCONbits.GIE = 1; // Enable global interrupts
T1CON = 0x31; // Set Timer1 in 16-bit mode with 1:8 prescaler and internal clock source
TMR1H = 0xFF; // Set initial Timer1 register values
TMR1L = 0x7E;
while(1) {
if(!PORTDbits.RD6){
pattern = 0x18;
direction = 1;
}
else{
pattern = 0xC0;
direction = -1;
}
T1CONbits.TMR1ON = 1; // Start Timer1
while(T1CONbits.TMR1ON); // Wait for Timer1 to overflow
LATA = pattern; // Update LEDs
delayFunc(); // Delay between pattern transition
}
return -1;
}
// Timer1 interrupt service routine
void interrupt ISR() {
if (PIR1bits.TMR1IF) // Check if Timer1 overflowed
{
T1CONbits.TMR1ON = 0; // Stop Timer1
PIR1bits.TMR1IF = 0; // Clear Timer1 overflow flag
TMR1H = 0xFF; // Reset Timer1 register values
TMR1L = 0x7E;
LATAbits.LATA0 ^= 1; // Toggle the RUN LED (D10)
}
}
void delayFunc() {
for(int j = 0; j < count1; j++) {
for(int k = 0; k < count2; k++) {
asm("nop"); // No operation
}
}
}
```
Note that this code assumes that the proper configuration bits have been set based on the hardware setup and specific microcontroller being used.