I was trying to send and receive data between Raspberry pi and Arduino UNO.
I'm able to send and receive a string from Arduino to Pi using Serial.println
.
I spent hours searching a better tutorial or a solution. Couldn't find any.
The code below will send an answer('Got'
) to Arduino when it recieves a 'Hi'
from Arduino.
Simple Python code I'm using:
import serial
import time
ser = serial.Serial('/dev/ttyACM0',9600)
ser.flushInput()
while True:
s= ser.readline()
s= s.strip()
print (s.decode("utf-8"))
if (s.decode("utf-8") == "Hi"):
print("sending")
ans = "Got"
ans = ans.encode("utf-8")
ser.write(ans)
time.sleep(0.5)
Arduino code:
void setup() {
Serial.begin(9600); As
Serial.println("Hi"); // send the data
}
void loop() {
delay(1000);
if (Serial.available()) {
//define SerIn here
SerIn = //code for reading string goes here
if (SerIn=='Got') {
Serial.println('I got it');
}else{
Serial.println('Oopz');
}
}
}
I tried this:
String SerIn;
SerIn = Serial.readStringUntil('\n');
This throws an error while compiling.
error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]
In file included from /usr/share/arduino/hardware/arduino/cores/arduino/Arduino.h:192:0,
from RPI_ARDSerial.ino:2:
/usr/share/arduino/hardware/arduino/cores/arduino/WString.h:130:16: note: initializing argument 1 of ‘unsigned char String::operator==(const char*) const’
unsigned char operator == (const char *cstr) const {return equals(cstr);}
String SerIn;
trychar SerIn[];
If that works I'll make it a proper answer. A string is really a character array, and that is what it is expecting.char SerIn[]; SerIn = Serial.readStringUntil('\n');
gives an error:storage size of ‘SerIn’ isn’t known
Is thisSerial.readStringUntil('\n');
part correct?SerIn[];
with a big enough buffer. Maybechar SerIn[16];