I connected my arduino uno to my system and then using serial tried writing and reading data but there is a problem which I found when I tried giving arduino crafted messages. My arduino code is pretty simple.
void setup() {
Serial.begin(115200);
}
void loop() {
if (Serial.available() > 0) {
String data = Serial.readStringUntil('\n');
Serial.print(" You sent me: ");
Serial.println(data);
}
}
and my python code on my system
#!/usr/bin/env python3
import serial
import time
if __name__ == '__main__':
ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1)
ser.flush()
while True:
string=input("Enter the string: ")
ser.write(str.encode(string))
line = ser.readline().decode('utf-8').rstrip()
print(line)
time.sleep(0.01)
Now this gives me ability to write instructions to my arduino but following sequences of communication occur
└──╼ $python3 serial_communication.py
Enter the string: a
Enter the string: v
Enter the string: v
You sent me: v
Enter the string: s
You sent me: v
Enter the string: d
Enter the string: r
You sent me: sd
Enter the string: d
You sent me: r
Enter the string: s
Enter the string: e
You sent me: ds
Enter the string: r
You sent me: e
Enter the string:
Looking at them I understand that this might be a problem with my code or I am using the wrong protocol.
input()
function does not preserve the terminating\n
.