Search code examples
cbit-shiftatmega

Bit Shifting out of register with >>1


I am using an Atmega 16 on a STK500 Programmer Board. im Trying to Turn on the leds on DDRA starting on Led0 with 0b00000001 to Led7 with 0b1000000. It seems like i push the set bit out of the register with a >> shift. Shouldnt it just move 1 to the right? I have this snippet

# define F_CPU 8000000UL
#include <util/delay.h>
#include <avr/io.h>

int main(void)
{
    DDRA=0xFF;
    char leds=0x01;
    while(1)
    {
        if (leds==0x01)
        {
            for (int i=0;i<8;i++)
            {
                PORTA=~leds;
                leds=leds<<1;
                _delay_ms(300);
            }
        }
        else
        for (int x=0;x<8;x++)
        {
            leds=leds>>1;
            PORTA=~leds;
            _delay_ms(300);
        }

    }
}

it seems like this part

for (int x=0;x<8;x++)
            {
                leds=leds>>1;
                PORTA=~leds;
                _delay_ms(300);
            }

pushes the bit out of the register, but it should not. am i making a mistake?


Solution

  • You are shifting the 1 out in the first loop. And you are not seeing because you update the display before the shift.

    At the end of the iteration with i = 0, leds will be equal to 0x02. So the following this logic you get:

    i, leds (end of the loop)
    0, 0x02
    1, 0x04
    2, 0x08
    3, 0x10
    4, 0x20
    5, 0x40
    6, 0x80
    7, 0x00