I have a litle question regarding the conversion from decimal to 8 bitbinary from numbers read from the serial port. When I use the code below , when I send the number 2 i get this output 00110010
Clearly this is wrong but the question is how do i make this whit the right output (00000010)
Thanks in advance and with best regards Ben
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
for (int b = 7; b >= 0; b--)
{
Serial.print(bitRead(incomingByte, b));
}
Serial.println();
}
Because you are sending an ASCII "2" not the number 2. The binary for ASCII "2" is 00110010 or 0x32 hex or 50 decimal. If you are only interested in converting single digit numbers you can just subtract 0x30. However, you should check to make sure a numeric character is entered and not an alpha character.