So I have a byte
-array representing the display attached to my Arduino:
byte theDisplay[8] = {
B00000000,
B00000000,
B00000000,
B00000000,
B00000000,
B00000000,
B00000000,
B00000000
};
Now I want to flip a single bit at an arbitrary position:
theDisplay[3][6] = 1;
This (probably) faulty method produces these errors:
In function 'void setup()':
sketch_sep14c:13:18: error: invalid types 'byte {aka unsigned char}[int]' for array subscript
theDisplay[3][6] = 1;
^
exit status 1
invalid types 'byte {aka unsigned char}[int]' for array subscript
Is there an easy way to flip a single bit working with indexes like shown above?
-
arduino.cc/reference/en Bits and Bytes sectionJuraj– Juraj ♦2021年09月14日 20:15:57 +00:00Commented Sep 14, 2021 at 20:15
-
@Juraj I was aware of that, but I couldn't figure out how to set the 6th bit of the 3rd item in the array to 1.gurkensaas– gurkensaas2021年09月14日 20:21:47 +00:00Commented Sep 14, 2021 at 20:21
1 Answer 1
The error occurs, because you try to use the syntax for a 2 dimensional array with a 1 dimensional array (since you have an array of bytes, not bits, and a microcontroller always works with at least one byte). For accessing the individual bits you need to use bitwise operators. For example this:
theDisplay[3] |= (1 << bitnumber); // for setting the bit
theDisplay[3] &= ~(1 << bitnumber); // for clearing the bit
with bitnumber
being the number of the bit to change counted from least significant bit (in the binary representation in your code the rightmost digit) to most significant bit (the leftmost digit).
If you want to know, what exactly this does, you can google for bitwise operators in C++.
-
2Arduino way is the bitSet function arduino.cc/reference/en/language/functions/bits-and-bytes/…2021年09月14日 20:16:50 +00:00Commented Sep 14, 2021 at 20:16
-
1Thanks for your answer. Do I understand correctly that the top one sets the bit to 1 and the lower one sets the bit to 0?gurkensaas– gurkensaas2021年09月14日 20:17:15 +00:00Commented Sep 14, 2021 at 20:17
-
2There is also
theDisplay[3] ^= (1 << bitnumber);
for toggling the bit.Edgar Bonet– Edgar Bonet2021年09月14日 20:23:38 +00:00Commented Sep 14, 2021 at 20:23 -
2@gurkensaas Yes, that is what "setting" and "clearing" means.2021年09月14日 21:45:05 +00:00Commented Sep 14, 2021 at 21:45