I want to send a number between 0 and 120 as a byte over Serial port. I'm working on a project that involves sending ultrasonic sensor readings over Bluetooth to an Android. I would like to send the entire reading as a byte and I think this can be done because an signed byte ranges from -128 to 127. However, the byte received in my Android app doesn't show the correct sensor reading. Here's the relevant code snippet:

  while (true){
      //ultrasonic sensor sends out signal
      digitalWrite(trigPin, LOW);
      digitalWrite(trigPin, HIGH);
      digitalWrite(trigPin, LOW);
      pinMode(echoPin, INPUT);
      duration = pulseIn(echoPin, HIGH);

      cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
      inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
      // max range is 156 inches, but our app will only display up to 100 inches
      inches = min(127, inches);
      Serial.print(inches, BIN);

In my Android app written in Java I read the value like this:

b = (byte) inputStream.read();

For example, if inches is 100 and I send that over Serial port, how can I expect to get the same reading in my Android app?

1 Answer 1


The problem is the BIN in your print statement. Everything is ALWAYS binary. The BIN means to break that binary up into ascii digits 0 and 1. So if you send

Serial.print(21, BIN);

then the print function takes 21 as a binary number, 00010101 and then sends those binary digits as ascii. So what goes out on the wire is 8 separate bytes, it goes 48, 48, 48, 49, 48, 49, 48, 49 as 48 and 49 are the ascii codes for 0 and 1.

What you want to do is just to send the raw byte. So use Serial.write instead. The print functions convert things to ascii representations but the write function just sends the raw bytes out. So if you write:


Assuming that inches is a byte type variable then it just sends the raw byte out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.