In one of my recent projects, I had to read a few digital inputs of an Arduino board into an integer variable as a binary number. My initial thought was to use direct register addressing, but later on, I came up with two other methods which work really well. Here on my blog, I share all three of them, hoping that these would help someone else as well.
Note: Pull down resistors MUST be used for each example.
void setup() {
Serial.begin(9600);
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,INPUT);
pinMode(5,INPUT);
}
void loop() {
int b0 = digitalRead(2);
int b1 = digitalRead(3);
int b2 = digitalRead(4);
int b3 = digitalRead(5);
int output=b0+(2*b1)+(4*b2)+(8*b3); //create the binary number
Serial.println(output);
delay(100);
}
2. Using BitShiftLeft (<<)
void setup() {
Serial.begin(9600);
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,INPUT);
pinMode(5,INPUT);
}
void loop() {
int b0 = digitalRead(2);
int b1 = digitalRead(3);
int b2 = digitalRead(4);
int b3 = digitalRead(5);
b1=b1<<1; //Shift the second bit by one binary place
b2=b2<<2; //Shift the third bit by two binary places
b3=b3<<3; //Shift the fourth bit by three binary places
int output=b0+b1+b2+b3; //add them together
Serial.println(output);
delay(100);
}
3. Reading the registers directly - Simplest method so far
In AVR microcontrollers, there is a register called Chip Register, which stores the input value of a particular group of pins (a port). In This example, Chip register is read and assigned directly to an int variable.
void setup() {
Serial.begin(9600);
}
void loop() {
DDRC=0x00; //Set all the pins of PortC to be inputs (A0 to A5 on Arduino Uno)
int a=PINC; //Read the input pins directly into a binary number
Serial.println(a);
delay(500);
}
This last code is amazingly simple, and lightweight. It could be way more useful when combined with Arduino Core functions.