I am trying to understand the example code about Encoding the states of DIP switch into number. I have already explaned everthing except the code they use for encode the binery to number.
* This example code is in the public domain
*
* Tutorial page: https://arduinogetstarted.com/tutorials/arduino-dip-switch
*/
#define POSITION_NUM 4[enter image description here](https://i.sstatic.net/82z3qGwT.png)
#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);
}
I expect you guys could give me explaination about these problems. It would be ideal to consist of the code function because I have dove into many websites without getting any results. I appreciate it.
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.