Search code examples
cpic18

I need to reverse the order of LED colors in my board


I need to reverse the order of my LED colors into 'PORT D' from the original sequence in 'PORT B'. My original colors in 'PORT B' are Blue, Purple, Green, Red, Yellow, Turquoise, White, and no color. Now I need to reverse the order in 'Port D'. I am having trouble in my while loop with the proper operation.

#include <math.h> 
#include <p18f4620.h>
#pragma config OSC = INTIO67
#pragma config WDT = OFF
#pragma config LVP = OFF
#pragma config BOREN = OFF

void Delay_One_Sec(){
for(int I=0; I <17000; I++);}

void main(){
TRISA = 0xff;
TRISB = 0x00;
TRISC = 0x00; 
TRISD = 0x00;
ADCON1 = 0x0f;

while (1)
{
    for(char i=0;i<8;i++)
    {
     PORTB = i;
     PORTD = i<<2;
     
     Delay_One_Sec();
     Delay_One_Sec();
    }
}

Solution

  • If you want to iterate the sequences [0, 1, ..., 7] and [7, 6, ..., 0] together, just use arithmetic:

    #include <stdio.h>
    
    int main(void) {
        for (int i=0; i < 8; i++) {
            int forward = i;
            int backward = 7 - i;
            printf("forward: %d, backward: %d\n", forward, backward);
        }
        return 0;
    }
    
    $ ./a.out 
    forward: 0, backward: 7
    forward: 1, backward: 6
    forward: 2, backward: 5
    forward: 3, backward: 4
    forward: 4, backward: 3
    forward: 5, backward: 2
    forward: 6, backward: 1
    forward: 7, backward: 0