Ahmed Safwat - 1 year ago 123

C Question

Answer Source

```
PORTD |= ((counter%8)<<5);
```

this is just shorthand for

```
PORTD = PORTD | ((counter%8)<<5);
```

`counter%8`

is simply counter modulo 8. Therefore, the result of `counter%8`

will always be in the range of 0..7

`<<5`

is doing a binary left shift on the result of `counter%8`

so thinking in 8 bit binary,

`0000 0001`

becomes `0010 0000`

`0000 0111`

becomes `1110 0000`

etc..

Assuming PORTD is and 8 bit address, this code is modifying the most significant 3 bits of PORTD.

```
PORTD = PORTD | 00000000b // 1st iteration
PORTD = PORTD | 00100000b // 2nd iteration
PORTD = PORTD | 01000000b // 3rd iteration
PORTD = PORTD | 01100000b // 4th iteration
PORTD = PORTD | 10000000b // 5th iteration
PORTD = PORTD | 10100000b // 6th iteration
PORTD = PORTD | 11000000b // 7th iteration
PORTD = PORTD | 11100000b // 8th iteration
PORTD = PORTD | 00000000b // 9th iteration
PORTD = PORTD | 00100000b // 10th iteration etc...
```