No, your code is not correct. There are several issues:
1. The for loop in the main function should be `for(int i=0; i<=8; i++)` instead of `for(int i=0; i<8; i++)`. This is because you want the loop to run for 8 iterations, including the last iteration where `i` equals 8.
2. In the if condition `if(PORTDbits.RA5 == 0)`, you should check if `SW3` is pressed and held down, not just if it is released. So the condition should be `if(PORTDbits.RA5 == 1)`.
3. The loop in the left to right sequence should start from `j=6`, not `j=7`. This is because `j` should be the index of the leftmost LED, which is at index 6 in a 7-segment display.
4. In the left to right sequence, you should use `LATA &= ~(1<<j);` instead of `LATA |= (1<<j);`. This is because you want to turn on the LEDs one by one, not turn them off one by one.
5. You should place the `delayFunc();` function call inside the for loop in both sequences, not outside the loop. This is because you want to delay the execution after each LED is turned on, not after the entire sequence is completed.
Here is the updated code:
```c
void main(void) {
TRISA = 0x00;
LATA = 0x00;
while(1) {
int i;
int j;
// Right to Left sequence
for(int i=0; i<=8; i++) {
LATA = (1 << i);
delayFunc();
}
// Left to Right sequence if SW3 is pressed and held
if(PORTDbits.RA5 == 1) {
for(j=6; j>=-1; j--) {
LATA &= ~(1<<j);
delayFunc();
}
}
}
return -1;
}
void delayFunc(void){
int i, j, k;
for(i = 0; i < 1000; i++){
for(j=0; j < 20; j++){
k = j;
}
}
}
```
Utilize SW3 of the explorer 16 board to change the direction of the Knight Rider Pattern. Any time, if SW3 is pushed down and hold, the above pattern starts from LEFT to RIGHT and when SW3 is released, the pattern walks from RIGHT to LEFT.
Is my code below correct?
void main(void) {
TRISA = 0x00;
LATA = 0x00;
while(1) {
int i;
int j;
// Right to Left sequence
for(int i=0; i<8; i++) {
LATA = (1 << i);
delayFunc();
}
// Left to Right sequence if SW3 is pressed
if(PORTDbits.RA5 == 0) {
for(j=7; j>=-1; j--) {
LATA |= (1<<j);
delayFunc();
}
}
}
return -1;
}
void delayFunc(void){
int i, j, k;
for(i = 0; i < 1000; i++){
for(j=0; j < 20; j++){
k = j;
}
}
}
1 answer