1

How can I use bitRead() to toggle between 3 LEDs? I have 3 LEDs - red, green, blue - and I have these 4 stages:

  1. Red ON and green, blue OFF
  2. Green ON and red, blue OFF
  3. Blue ON and red, green OFF
  4. All OFF

and repeat.

  • 2
    Do you have some code for us? – zx485 Nov 19 '16 at 21:05
1

To toggle LED you can do:

uint8_t BITval=1; //initialization B00000001

void toggle()
{
 digitalWrite(RED_pin,BITval&1);    //Bxxxxxxx1
 digitalWrite(BLUE_pin,BITval&2);   //Bxxxxxx1x
 digitalWrite(GREEN_pin,BITval&4); //Bxxxxx1xx

 BITval=BITval<<1;
 if (BITval== B00010000) //reset BIT value
    BITval=1;
}

And assuming you want to do bitRead() to read input from active-low push button which is connected to PORT-x, PIN-y

you can do:

if (bitRead(PORTx,PINy))==0) 
toggle();
| improve this answer | |
0
uint8_t     value_leds = 0;

// Toggle LEDs
void ToggleLeds()
{
    if ( value_leds == 0 )
        value_leds = 1;
    else
        value_leds = (value_leds << 1) & 0x0F;
}

To test if bit n is set:

if ( bitRead(value_leds, n) != 0 )

or

if ( (value_leds & (1<<n)) != 0 )
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.