I've written the below code and I'm wondering why the variable led_state is not holding a shifted value when a button is pressed. Initially bit0 of 4 leds is on then when the button is pressed the led is shifted left so bit1 is on then bit2 then bit3 etc but after a while the led state go's back to bit0. I was expecting when button is 0 it would keep on returning the shifted value. Can anyone tell me why its not? I was thinking that it might have something to do with the scope of led_state but it is declared as a global variable.
Code:
#pragma config FOSC = INTOSCIO
#include <stdio.h>
#include <pic16f785.h>
#include <xc.h>
#include <stdlib.h>
struct led_addr_bits {
unsigned bit7 : 1;
unsigned bit6 : 1;
unsigned bit5 : 1;
unsigned bit4 : 1;
unsigned bit3 : 1;
unsigned bit2 : 1;
unsigned bit1 : 1;
unsigned bit0 : 1;
}led_addr_bits;
char inc_led_state(char);
char led_state = 0x01;
char inc_state;
int main()
{
OSCCON = 0x39;
ANSEL1bits.ANS11 = 0;
TRISBbits.TRISB5 = 1;
TRISCbits.TRISC6 = 0;
TRISCbits.TRISC7 = 0;
TRISBbits.TRISB7 = 0;
while(1)
{
led_state = inc_led_state(led_state);
led_addr_bits.bit3 = led_state >> 3;
led_addr_bits.bit2 = led_state >> 2;
led_addr_bits.bit1 = led_state >> 1;
led_addr_bits.bit0 = led_state;
PORTBbits.RB7 = led_addr_bits.bit0;
PORTCbits.RC7 = led_addr_bits.bit1;
PORTCbits.RC6 = led_addr_bits.bit2;
PORTCbits.RC3 = led_addr_bits.bit3;
}
}
char inc_led_state(char led_state)
{
if(PORTBbits.RB5==0)
{
inc_state = led_state;
}
if(PORTBbits.RB5==1)
{
while(PORTBbits.RB5==1);
inc_state = led_state << 1;
}
return inc_state;
}