How do I receive an entire string as opposed to 1 character at a time on the arduino?
The problem is that the Arduino is looping around so fast, it will execute the if (numBytesAvailable > 0)
line several times between each character arriving through the serial port. So as soon as a character does arrive, it grabs it, loops from zero to one, and prints a single character out.
What you should do is send an end of line character ('\n') after each command from your Python program. Then have your Arduino code buffer each character it receives and only act on the message once it receives the end-of-line character.
So if you change your Python code do send an end of line character, like so:
import serial
ser = serial.Serial('/dev/ttyACM1',9600)
ser.write("MOVE\n")
Then your Arduino code can be something like this:
// Buffer to store incoming commands from serial port
String inData;
void setup() {
Serial.begin(9600);
Serial.println("Waiting for Raspberry Pi to send a signal...\n");
}
void loop() {
while (Serial.available() > 0)
{
char recieved = Serial.read();
inData += recieved;
// Process message when new line character is recieved
if (recieved == '\n')
{
Serial.print("Arduino Received: ");
Serial.print(inData);
inData = ""; // Clear recieved buffer
}
}
}
Your Python script is sending four bytes, M
, O
, V
, and E
. How is the Arduino supposed to know that that's a single string? Consider that the Python code:
ser.write("MOVE")
is completely identical to
ser.write("MO")
ser.write("VE")
from the Arduino's point of view. Serial ports transfer characters, not strings.
In your code, the Arduino is fast (compared to the 9600 baud rate), so every time it calls Serial.available()
, it only sees one of those four characters. That's why you got the output you did.
What you'll need to do is come up with some way of delimiting strings, i.e. marking them in some way from Python so that the Arduino can append the individual characters that it receives into your high-level concept of a string.
Using lines is straightforward: send every string terminated with a newline character ('\n'
). On the Arduino, read characters and append them to your string. When you see a '\n'
, the string is over and you can print it.
if(Serial.available() > 0) {
str = Serial.readStringUntil('\n');
Serial.println(str);
The above code works perfect on my connection between Pi and Arduino