Hi,
I wrote a program (on Arduino Mega 2560 with newest IDE to this day) to read n digital inputs. Each input is 2^n if HIGH and 0 else. Then it sums all the inputs and prints the result. So it converts a binary number to a decimal (there might be easier way to do this, sorry i'm a newbie programmer). The problem is that the sum printed is always 0 even if some inputs are HIGH and I do not understand why.
Can someone help me, please ?
Thank you
int Qa = 2;
int Qb = 3;
int Qc = 4;
int Qd = 5;
int a;
int b;
int c;
int d;
void setup() {
Serial.begin(57600);
pinMode(Qa, INPUT);
pinMode(Qb, INPUT);
pinMode(Qc, INPUT);
pinMode(Qd, INPUT);
digitalWrite(Qa, LOW);
digitalWrite(Qb, LOW);
digitalWrite(Qc, LOW);
digitalWrite(Qd, LOW);
}
void loop() {
if (digitalRead(Qd) == HIGH)
{
int d=8;
Serial.print(1);
}
else {
int d=0;
Serial.print(0);
}
if (digitalRead(Qc) == HIGH)
{
int c=4;
Serial.print(1);
}
else {
int c=0;
Serial.print(0);
}
if (digitalRead(Qb) == HIGH)
{
int b=2;
Serial.print(1);
}
else {
int b=0;
Serial.print(0);
}
if (digitalRead(Qa)==HIGH)
{
int a=1;
Serial.print(1);
}
else {
int a=0;
Serial.print(0);
}
int t=a+b+c+d;
Serial.print("=");
Serial.print(t);
Serial.print(" ");
delay(50);
}
Already answered by sherzaad while I was writing this but I give a little more information so I'll post it anyway:
pyroexplosif:
int a;
int b;
int c;
int d;
Here you declare a b c and d as global variables, which causes them to be zero initialized.
pyroexplosif:
if (digitalRead(Qd) == HIGH)
{
int d=8;
Serial.print(1);
}
Here you declare a local variable named d, and so on for the other variables
pyroexplosif:
int t=a+b+c+d;
So which version of these variables should be used here, the local ones, which may have non-zero values, or the global ones, which will always be zero? I think you can guess which is being used. So you have two choices:
Remove the global declarations from your sketch. There is no need for these variables to be globals in your current code.
Remove the local declarations of the variables from loop(), instead define the global variables in loop().