My question is why do we need to use bitwise operations to make assignements?
Because you're not assigning, you're modifying.
If you want to turn on just pin 3 (for example) you need to only control bit 3 of PORTB and leave the others alone.
That means you need to "or" the value of just bit 3 being on with the existing PORTB to turn the bit on, or AND it with the inverse (all pins on except bit 3) to turn it off.
To get the value of bit 3 you can remember that it's 4
, or you can just use 1<<3
to say "Bit 3" - or use the macro PORTB3
to make it more readable instead of just the number 3.
The operation is commonly known as "Read Modify Write" and in some low-end microcontrollers you have to take special care when doing it.
For example, if you want to control the output pin 3 and currently you have pins 2, 5 and 6 on and the rest of pins 0-7 off (those are the ones on port B on the Uno) the sequence may be like:
Turn on:
Calculate bit value 1<<3 => 0b00001000
Read PORTB => 0b01100100
OR the two values together => 0b01101100
Write to PORTB <= 0b01101100
Turn off:
Calculate bit value 1<<3 => 0b00001000
Invert it => 0b11110111
Read PORTB => 0b01101100
AND the two values together => 0b01100100
Write to PORTB <= 0b01100100
PORTB |= (1<<PORTB2); //set bit 2 and keep the rest unchanged
andPORTB = (1<<PORTB2); //set bit 2 and clear everything else
.