Setting and clearing a single bit, without changing any other bits, is a common task in AVR microcontroller programming. You will use these techniques over and over again.
When manipulating a single bit, it is often necessary to have a byte value in which only the bit of interest is set. This byte can then be used with bitwise operations to manipulate that one bit. Let's call this a bit value mask. For example, the bit value mask for bit 2 would be
00000100
and the bit value mask for bit 6 would be
01000000
.
Since the number
1
is represented in binary with only bit 0 set,
you can get the bit value mask for a given bit by left shifting 1
by the bit number of interest. For example, to get the bit value mask for bit
2, left shift 1
by 2.
To set a bit in C,
OR the value with the bit value mask.
uint8_t a = 0x08; /* 00001000 */ /* set bit 2 */ a |= (1<<2); /* 00001100 */Use multiple OR operators to set multiple bits.
uint8_t a = 0x08; /* 00001000 */ /* set bits 1 and 2 */ a |= (1<<2)|(1<<1); /* 00001110 */To clear a bit in C, NOT the bit value mask so that the bit of interest is the only bit cleared, and then AND that with the value.
uint8_t a = 0x0F; /* 00001111 */ /* clear bit 2 */ a &= ~(1<<2); /* 00001011 */Use multiple OR operators to clear multiple bits.
uint8_t a = 0x0F; /* 00001111 */ /* clear bit 1 and 2 */ a &= ~((1<<2)|(1<<1)); /* 00001001 */To toggle a bit in C, XOR the value with the bit value mask.
uint8_t a = 0x0F; /* 00001111 */ /* toggle bit 2 */ a ^= (1<<2); /* 00001011 */ a ^= (1<<2); /* 00001111 */
Source http://www.micahcarrick.com/tutorials/avr-microcontroller-tutorial/avr-c-programming.html
Tidak ada komentar:
Posting Komentar