1

I'm trying to send data from an Arduino to an Android device.

I saw an online guide for that which provided this code:

void setup() 
{ 
  Serial.begin(115200);
} 

void loop() 
{ 
  byte msg[64]; 
  int len = Serial.available();
  if (len > 0)
  {
    len = Serial.readBytes((char*)msg, sizeof(msg)); // readBytes seems to need a char* not a byte*
    Serial.write(msg, len);
  }
}  

I tried that example and it is working perfectly!

But when I put Serial.write("3"); in the setup loop after Serial.begin(115200); it appears as question mark on my Android device, I guess that I'm not sending it as a byte, I searched online but without any luck.

3
  • 1
    What appears in the serial terminal when connected to a PC? – BrettAM Jan 10 '16 at 18:52
  • How are u communicating with the android device? Don't u mean that you are sending data from your PC to the android, through the arduino? – SoreDakeNoKoto Jan 10 '16 at 21:01
  • It sounds like you have the Arduino hooked up to the Android via a USB cable and are using a terminal emulator on the Android to communicate with the Arduino, with the code in loop() doing a simple echo of what you type in the terminal emulator. Is that right? Everything works using the example above, but when you modify it to send the string "3" to the Android, kind of like a prompt, the "3" is not displayed correctly. Am I missing something? – dlu Jan 10 '16 at 22:47
2

Start by changing it to Serial.write("3", 1);

Does that help, you're missing the second parameter to the Serial.write call, which is the number of characters (bytes) to write. 

1
0

I think this is a timing issue. It is fairly normal for a garbage byte or two to be received shortly after doing a Serial.begin() because the transition of "not defined" (or high impedance) output to Serial (which is normally all 1-bits) can cause the receiver to think it got a start bit, and then misinterpret what follows.

Try adding a short delay after Serial.begin. You could also try a pull-up resistor on the serial Tx line to ensure it is high prior to Serial.begin being called.

Your use of Serial.available effectively builds in a delay.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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