Accepting multiple inputs from Pi and sending to Arduino and storing all the values in Variables

Hello,
I am trying to communicate between Raspberry Pi and Arduino using serial. I want to send input data from Pi to Arduino and Arduino should store in variables all the values from Pi. I am unable to read and store data in Arduino Variables although my python code is working fine. please help me with it.

Python Code (Working)

import serial
import time

if __name__ == '__main__':

    ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    
    ser.reset_input_buffer()
   
    while True:
        
        pul, csol, sol, de = input("pulse = ") ,input("From Solenoid = "),input("To Solenoid = "),input("delay in minutes = ")
        print(pul,csol,sol,de)
        ser.write(pul.encode('utf-8'),csol.encode('utf-8'),sol.encode('utf-8'),de.encode('utf-8'))        

Arduino Code

int pulse, From_Solenoid, To_Solenoid, Delay;

void setup() {
  Serial.begin(9600);

}
void loop() {
  if(Serial.available()>0){
    int pulse = Serial.readStringUntil('\n');
    int From_Solenoid = Serial.readStringUntil('\n');
    int To_Solenoid = Serial.readStringUntil('\n');
    int Delay = Serial.readStringUntil('\n');
    Serial.println(pulse);
    Serial.println(From_Solenoid);
    Serial.println(To_Solenoid);
    Serial.println(Delay); 
}
}

What kind of Arduino is this? How is it connected to the Pi?

It is port number when you connect Arduino to Raspberry Pi

In Arduino you wait for newline after each reading:

I don't know python well, but does this line insert newlines between values?

You could consider using an RPC library and Python client.

The Arduino code could look like this:

#include <simpleRPC.h>

void solenoid(int pulse, int from, int to, int wait) {
  Serial.println(pulse);
  Serial.println(from);
  Serial.println(to);
  Serial.println(wait);
}

void setup() {
  Serial.begin(9600);
}

void loop() {
  interface(Serial,
    solenoid, F("solenoid: Solenoid stuff. @pulse: Pulse. @from: From. @to: To. @wait: Wait."));
}

and this would be the code on the Raspberry Pi:

from simple_rpc import Interface

interface = Interface('/dev/ttyACM0')

interface.solenoid(1, 2, 3, 4);

Alternatively, you could send delimited text and use a text parser library, e.g.,

#include <textparser.h>

TextParser parser(", ");  // Delimiter is a comma followed by a space.
int pulse, From_Solenoid, To_Solenoid, Delay;

void loop() {
  char line[80];

  // Assume `line` is of the form "1, 2, 3, 4\n".
  Serial.readBytesUntil('\n', line, sizeof(line));
  parser.parseLine(line, pulse, From_Solenoid, To_Solenoid, Delay);
  Serial.println(pulse);
  Serial.println(From_Solenoid);
  Serial.println(To_Solenoid);
  Serial.println(Delay); 
}

And of course you can come up with your own protocol.

1 Like

thankyou

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.