LittleJubb
LittleJubb

Reputation: 21

Python to Arduino Serial Communication-Manual Input Works but Variable Does Not

I am communicating from raspberry pi using python to my Arduino via usb and serial communication. I got it to work perfectly when I ask for an input but when I try and save a variable and push that through, it doesn't work. I think the Arduino is reading the serial until a newline is found. When I type input from python and press enter, the arduino successfully recognizes a newline and executes the code. However, when I save a string with \n at the end, the Arduino does not correctly receive the string and the rest of the code does not continue.

Is there an easy way to fix this, or even a longer way to trick python by still asking for an input, but the computer automatically types in what I need my variable to be and then presses enter?

Here is my python code that works:

import serial
import time

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    ser.flush()
    
    while True:
                direction_distance = input("Enter String :")
                
                ser.write(direction_distance.encode('utf-8'))
                
                time.sleep(0.5)
                
                receive_string=ser.readline().decode('utf-8').rstrip()
                
                print(receive_string)

Here is Arduino Code that works:

void setup(){
Serial.begin(9600);
}
void loop(){
 
  if(Serial.available() > 0) {
    String data = Serial.readStringUntil('\n');

    //Rest of code continues below with newly imported 'data'
  }
}

Here is my python code that sends data to the Arduino, but the Arduino fails to recognize the newline '\n'

import serial
import time

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    ser.flush()
    
    while True:
                direction_distance = "2000\n"
                
                ser.write(direction_distance.encode('utf-8'))
                
                time.sleep(0.5)
                
                receive_string=ser.readline().decode('utf-8').rstrip()
                
                print(receive_string)

Upvotes: 0

Views: 427

Answers (1)

LittleJubb
LittleJubb

Reputation: 21

There wasn't a long enough delay for the strings to go fully go through. I was able to fix this issue changing the sleep to 2 seconds. (And by removing the \n)

import serial
import time

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    ser.flush()
    
    while True:
                direction_distance = "2000"
                
                time.sleep(2)

                ser.write(direction_distance.encode('utf-8
                
                receive_string=ser.readline().decode('utf-8').rstrip()
                
                print(receive_string)

Upvotes: 2

Related Questions