Serial Communication between Raspberry Pi and Arduino

Hello,

I want to input Strings into a Programm running on my Arduino.
The String is entered on a Website, saved on the Webserver.
A Python Programm is reading the String and sending it to the Arduino. (the Arduino uses it to morse/blinnk it)

This works quite well, wenn the Arduino is connected to my laptop.
It sometimes works, when I'm doing the same thing with a raspberry pi (Arduino connected same way, with an USB cable to the Raspberry). Sometimes only the first letter of the string arrives, sometimes nothing happens.

Im posting parts of the arduino and my Python script. Am I doing something wrong? How to make the behavior a little bit more predictable?

Best regards

Adriana

This is, how the Arduino gets the String

void setup()
{

  Serial.begin(9600);
  while (!Serial) {
    ; }



void loop()
{
  if (Serial.available() > 0) {

    instring = Serial.readString();
            
  }
Serial.println(instring);

...

And this, how the python script is sending the data to the arduino (it looks up the text on a webserver and writes something back...this part has not much to do with the serial problem, I suppose, but to be sure, I left the code as it is)

import serial
import urllib

import requests
import time

while 1:
  print("hello");
  time.sleep(4);


  link_ready = 'http://www.mikolaskova.cz/r57/ready.txt'
  f_ready = urllib.urlopen(link_ready)           
  myfile_ready = f_ready.readline()  

  if myfile_ready=="no":
    link = 'http://www.mikolaskova.cz/r57/text.txt'
    f = urllib.urlopen(link)           
    myfile = f.readline()  
    print myfile
  
    ser= serial.Serial('/dev/ttyACM0',9600)
    
    
    if ser.isOpen():
      ser.write(myfile)
      response = ser.read(ser.inWaiting())
    response = urllib.urlopen("http://www.mikolaskova.cz/r57/done.php")
    data = response.read()
    print data

  else:
    print "nothing to do-ready: no"

serial input basics

Maybe this will help.

or this

read string until (lf)

assuming the pi sends a linefeed at the end of the string.

You might also like to look at this Python-Arduino demo.

...R

Thank you very much. My code works well with a normal computer, so after reading some of your links, I suppose, it does not work properly with the pi, because it's slower?

It looks like your Python code runs in a continuous loop and opens the serial port each time through the loop.

When the serial port is opened an Uno or Mega will reset. Your code should only open the serial port once. And it should then allow time for the Arduino to reset.

If you are using a Leonardo this may not matter.

In some Python code I was working on it was necessary to include
ser.rtscts = True
to force the reset.

I have a suspicion that this was not necessary with a different version of Python (different version of Linux). Maybe that is treated differently on the RPi and on your PC.

...R