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.
2 Answers 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.
-
2The second parameter isn't necessary for c strings, it will read until it sees the null terminator arduino.cc/en/Serial/WriteBrettFolkins– BrettFolkins2016年01月10日 18:52:43 +00:00Commented Jan 10, 2016 at 18:52
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.
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?