Search code examples
c++carduinoled

Why are these two values not equal on arduino?


I am making a little arduino binary calculator.

I have the code run some little math problem: ✓

I convert the answer from decimal to binary: ✓

I loop through the binary answer with a for loop and power on LEDs on a bread board to display the answer: ✗

//First led in pin 2
void setup()
{
  Serial.begin(9600);
}
//I have the code run some little math problem:Check
int a=2;
int b=5;
int answer=b-a;


int myNum = answer;
void loop(){
//I convert the answer from decimal to binary:Check
int zeros = 8 - String(myNum,BIN).length();
String myStr;
for (int i=0; i<zeros; i++) {
    myStr = myStr + "0";
}
myStr = myStr + String(myNum,BIN);         
Serial.println(myStr);

//I loop through the binary answer with a for loop 
//and power on LEDs on a bread board to display the answer:Not check

for(int i=2;i<=9;i=i+1){

//This part doesn't work

if(int(myStr[i-2])==1){
        digitalWrite(int(i), HIGH);
    }else{Serial.println(myStr[i-2]);}
}
while(true){}
}

for some reason it says int(myStr[i-2]) is never equal to 1.

Thanks in advance for the help.


Solution

  • The int() conversion is likely not doing what you think it does. It does not convert the value from a numerical string to a binary value. Instead you probably want to check to see if the values in the string are ascii digits.

    if(myStr[i - 2] == '1')
    //                 ^^^ single quotes to specify character value.
    {
        digitalWrite(int(i), HIGH);
    }
    else
    {
        Serial.println(myStr[i - 2]);
    }