Register bit settings and resulting function of port pins
register bits → pin function↓ |
DDRx.n | PORTx.n | PINx.n |
tri stated input | 0 | 0 | read data bit x = PINx.n; |
pull-up input | 0 | 1 | read data bit x = PINx.n; |
output | 1 | write data bit PORTx.n = x; |
n/a |
Bit operations: &, |, ^, >>, <<, ~
Operator | Description | Example | Res. |
& | bit AND | 11110000 & 0b00110001; | 00110000 |
| | bit OR | 01000001 | 0b00010000; | 01010001 |
^ | bit EXLUSIVE OR (XOR) | 00001001 ^ 00010000; | 00000001 |
~ | bit NOT(<one’s complement) | ~11110000; | 00001111 |
<< | bit LEFT SHIFT | 00000001 << 1; 00000001 << 2; 00000111 << 1; 00001110 << 2; |
00000010; 00000100; 00001110; 00011100; |
>> | bit RIGHT SHIFT | 00010000 >>1; 00010000 >>2; 11100111 >>1; 11100010 >>2; |
00001000; 00000100; 01110011; 00111000; |
Bit mask
Bit number | Binary representation | Sintax | Hex value |
0 | 0b00000001 | 1 | 0×01 |
1 | 0b00000010 | (1<<1) | 0×02 |
2 | 0b00000100 | (1<<2) | 0×04 |
3 | 0b00001000 | (1<<3) | 0×08 |
4 | 0b00010000 | (1<<4) | 0×10 |
5 | 0b00100000 | (1<<5) | 0×20 |
6 | 0b01000000 | (1<<6) | 0×40 |
7 | 0b10000000 | (1<<7) | 0×80 |
Examples in C (GCC)
Setting a single bit (without changing any other bits)
1 2 3 4 5 6 |
DDRA = 0b00100000; /* 0x20 */ /* set bit 2 */ DDRA = DDRA | 0b00000100; /* long syntax*/ DDRA = DDRA | (1<<2); /* shorter syntax*/ DDRA|= (1<<2); /* even shorter syntax*/ /*rezult 0b00100010*/ |
Clearing a single bit (without changing any other bits)
1 2 3 4 5 6 7 8 |
DDRA= 0x0F; /* 0b00001111 */ /* clear bit 2 */ DDRA = DDRA | 0b11111011; DDRA = DDRA | ~0b00000100; DDRA = DDRA | ~(1<<2) DDRA |= ~(1<<2); /* result 00001011 */ |
Toogle a single bit (without changing any other bits)
1 2 3 4 |
DDRA= 0b00001111; /* 0x0F */ DDRA ^= (1<<2); /* toggle bit 2 */ /* result 00001011 */ |
1 2 3 4 |
DDRA= 0b00001011; /* 0x0B */ DDRA ^= (1<<2); /* toggle bit 2 */ /* result 00001111 */ |
Checking single bit (without changing any bits)
1 2 3 4 5 6 7 8 9 |
if (PINA | (1<<2)) { /* PINA.2 is set*/ } else { /* PINA.2 is not set*/ } |
you are awesome man. I was searching for this in last four months
Thank you! 🙂