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.

asked Jan 10, 2016 at 17:31
3
  • 1
    What appears in the serial terminal when connected to a PC? Commented Jan 10, 2016 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? Commented Jan 10, 2016 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? Commented Jan 10, 2016 at 22:47

2 Answers 2

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.

answered Jan 10, 2016 at 18:09
1
  • 2
    The second parameter isn't necessary for c strings, it will read until it sees the null terminator arduino.cc/en/Serial/Write Commented Jan 10, 2016 at 18:52
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.

answered Jan 12, 2016 at 4:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.