I am trying to understand the example code about Encoding the states of DIP switches into a number. I don’t understand the code they use for encoding the binary into a number.
* This example code is in the public domain
*
* Tutorial page: https://arduinogetstarted.com/tutorials/arduino-dip-switch
*/
#define POSITION_NUM 4
#define ON LOW
#define OFF HIGH
// define the pins connected to the dip switch
const int SWITCH_PINS[] = { 2, 3, 4, 5 };
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set the DIP switch pins as inputs with pull-up resistors enabled
for (int i = 0; i < POSITION_NUM; i++)
pinMode(SWITCH_PINS[i], INPUT_PULLUP);
}
void loop() {
int encoded_state = 0;
for (int i = 0; i < POSITION_NUM; i++) {
int state = digitalRead(SWITCH_PINS[i]);
if (state == ON) //
encoded_state |= 1 << (POSITION_NUM - i - 1); // this is what I don't understand
}
}
I hope you guys can give me an explanation for the part I’ve marked in the code.
New contributor
Luong Anh Minh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1