How to set multiple bits simultaneously in a register

Hi there,

I'm using an ATtiny84 to blink two LEDs depending on a condition. Sometimes, it blinks only one LED, and the other blinks both. However, the code below sequentially lights up the LEDs. I know it's still fast for the human eye, but I wonder if anyone knows how I could set bits 4 and 5 of the PORTA register without changing the rest of the bits in the register.

#define OUT_L     4
#define OUT_R     5

bool bBit = 1;

void setup() {
  pinMode(OUT_R, OUTPUT);
  pinMode(OUT_L, OUTPUT);

  digitalWrite(OUT_R, LOW);
  digitalWrite(OUT_L, LOW);
}

void loop() {
      if (bBit){
        // digitalWrite(OUT_L, 1);
        // digitalWrite(OUT_R, 1);
        PORTA &=~(1<<(OUT_L));
        PORTA &=~(1<<(OUT_R));
      }
      else{
        // digitalWrite(OUT_L, 0);
        // digitalWrite(OUT_R, 0);
        PORTA |=(1<<(OUT_L));
        PORTA |=(1<<(OUT_R));
      }

  bBit = !bBit;
  delay(1000);
}
        PORTA &=~((1<<(OUT_L)) | (1<<(OUT_R)));
...

        PORTA |=((1<<(OUT_L)) | (1<<(OUT_R)));

Do you realise that your code only works by luck? You are lucky that the Arduino pin numbers, 4 & 5, happen, by chance, to be bits 4 & 5 in PORTA.

1 Like

If you want to toggle the output pins, you can do this by writing a 1 to the corresponding bit in the PINA register.

1 Like

thank you for the help.
appriciate it much!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.