Question

Hi. I have written a function that shifts LEDs to right. I used for loop and I want to convert it to if statements.

#include <mega8535.h> 
#include <delay.h>   

void main(void) {
    int bits = 0b11111110;  
    int i;              
    int j;              
    PORTA = 0xFF;   
    DDRA = 0xFF;   

    for(j = 0; j < 5; j++) {
        for(i = 0; i < 8; i++) {  
            PORTA = ((bits << i) | (bits >> 8-i));  
            delay_ms(500);                                                      
        }                                                   
        PORTA = 0b11111110;                                  
    }      
    PORTA = 0xFF;                       
}

How can I do that?

Était-ce utile?

La solution 2

Try this

    if(i==0){
    PORTA = ((bits<<0) | (bits >> 8));  
    delay_ms(500);
    i++;
    }
    if(i==1){
    PORTA = ((bits<<1) | (bits >> 8-1));  
    delay_ms(500);
    i++;
    }
    if(i==2){
    PORTA = ((bits<<2) | (bits >> 8-2));  
    delay_ms(500);
    i++}
    .
    .
    //so on up to i=7 

Autres conseils

To unroll a for loop you would just copy and paste it's contents, each time replacing it with the current value of the iterator.

So

for(i=0; i<8; i++)                 
{  
PORTA = ((bits<<i) | (bits >> 8-i));  
delay_ms(500);                                                      
}

would become

//i=0
PORTA = ((bits<<0) | (bits >> 8-0));  
delay_ms(500);  
//i=1
PORTA = ((bits<<1) | (bits >> 8-1));  
delay_ms(500); 
//i=2
PORTA = ((bits<<2) | (bits >> 8-2));  
delay_ms(500); 
//i=3
PORTA = ((bits<<3) | (bits >> 8-3));  
delay_ms(500); 
//i=4
PORTA = ((bits<<4) | (bits >> 8-4));  
delay_ms(500); 
//i=5
PORTA = ((bits<<5) | (bits >> 8-5));  
delay_ms(500); 
//i=6
PORTA = ((bits<<6) | (bits >> 8-6));  
delay_ms(500); 
//i=7
PORTA = ((bits<<7) | (bits >> 8-7));  
delay_ms(500); 

In VHDL for example, a for loop is converted to the equivalent unrolled loop.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top