Question

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.

Was it helpful?

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]);
}

OTHER TIPS

You should consider that in C a char is nothing more than an alias of an int so casting a char to int is a no-op. So the problem is that you are casting the character '1' or '0' to its int equivalent (its ascii code in fact). You should convert the char to a valid int (by subtracting 48 to a char in the range 48 - 57 you obtain the decimal conversion of the char) or simply checking it against a char value (so myStr[i-2] == '1')

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top