Sets (writes a 1 to) a bit of a numeric variable at a specific position. Useful when you're doing low-level bit manipulation, especially when working with hardware registers, flags, or memory-mapped I/O.
Use the following function to set the bit state on the n position of the x variable:
bitSet(x, n)
The function admits the following parameters:
x: the numeric variable whose bit to set.n: which bit to set, starting at 0 for the least-significant (rightmost) bit.The function returns the value of the numeric variable after the bit at position n is set.
Modify a given byte x by turning its 5th bit to 1:
uint8_t x = 0b10000001; // initial byte
void setup() {
Serial.begin(9600);
int index = 5; // index of the bit to modify
x = bitSet(x, index-1);
Serial.print("The resulting byte is: ");
Serial.println(x, BIN);
}
void loop() {
}
This is what the bitSet() function does behind the scenes:
#define bitSet(value, bit) ((value) |= (1UL << (bit)))