louis_f
September 14, 2021, 8:26pm
1
Hello,
I am working on a school project, for creating an arduino code to convert decimals to binary... i am a beginner and glad to have managed to create a working code. But there is on slight problem ... when i convert my number, 2 "1" appear in front of the value and i can't figure out where they're coming from
Example with number 5:
Thanks for your help, i have to hand this in next week .
Please post code, not pictures of code.
Please post results and expectations.
louis_f:
Example with number 5:
Did you mean '5'?
The result is as expected.
louis_f
September 14, 2021, 8:30pm
4
int incomingByte = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
// envoie une donnée sur le port série seulement quand reçoit une donnée
if (Serial.available() > 0)
{ // si données disponibles sur le port série
// lit l'octet entrant
incomingByte = Serial.read();
// renvoie l'octet reçu
Serial.print("Base 2 ->");
Serial.println((char)incomingByte, BIN);
}
}
My expectations are that it only gives "0101"
And it needs to work for any number from 1 to 9
Thought experiment for you... what should it print if you send it a letter, like 'x'?
Not my expectation.
'5' == 0x35 == 0b00110101
louis_f
September 14, 2021, 8:33pm
7
Well, 5 in binary is 0101 and thats what i would want it to give for this example if you see what i mean
Try. Hint - do computer keyboards have only numbers on them? How do you suppose that 'x' would be transmitted?
LarryD
September 14, 2021, 8:37pm
10
There is 5 and there is 5.
...like the 'x' in the right hand column of the chart above?
LarryD
September 14, 2021, 8:42pm
15
What code do you get printed for 0 (zero).
louis_f
September 14, 2021, 8:45pm
16
Ok, I will try that tomorrow, thanks
1 Like
hi @louis_f
Change this line of your sketch: "Serial.println((char)incomingByte, BIN);"
with this line: Serial.println((incomingByte & 0x0F), BIN);
and test to see if is what you want.
RV mineirin
Or even
Serial.println(incomingByte - '0', BIN);
or even
if ( isdigit(incomingByte) ) {
Serial.println(incomingByte - '0', BIN);
} else {
Serial.println(F("out of range - not numeric input") );
}
this one will print garbage values for inputs (:, ;, <, =, >, ?) :
Serial.println((incomingByte & 0x0F), BIN);
just as subtraction will print garbage values for any non-numeric character.
anon57585045:
this one will print garbage values for inputs (:, ;, <, =, >, ?) :
Only decimals must be converted.
RV mineirin