I need to transfer information between pyton script and arduino.
Data is always built like this "wheelbase:1000" wheelbase can be another word and 1000 can be another value, : is always the separator
Here is my python code:
import serial.tools.list_ports
import serial
import time
ports = list(serial.tools.list_ports.comports())
for p in ports:
print(p)
mcustring = str(ports[0]).split(" ")[0]
print(mcustring)
mcu = serial.Serial(mcustring, 9600)
mcu.timeout = 0.1
def write_read(x):
mcu.write(x.encode())
time.sleep(0.05)
data = mcu.readline()
return data
num = "wheelbase:1000\n"
for i in range(10):
print(i)
num = "wheelbase:1000"
value = write_read(num)
print(value) # printing the value
time.sleep(1) # wait 0.5 seconds
num = "wheelbase:500"
value = write_read(num)
print(value) # printing the value
time.sleep(1)
value = write_read(num)
print(num) # printing the value
time.sleep(1)
mcu.close()
and here is my arduino code:
String SerialRead1;
String SerialRead2;
double Wheelbase = 0;
double Level0 = 0;
double Gradient = 0;
void setup() {
// put your setup code here, to run once:
Serial . begin ( 9600 ) ; // turn on Serial Port
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
while (Serial.available() > 0) {
SerialRead1 = Serial.readStringUntil(':') ;
SerialRead1.trim();
SerialRead2 = Serial.readStringUntil('\n') ;
SerialRead2.trim();
Serial.print ( "string1: " ) ;
Serial.println(SerialRead1);
Serial.print ( "string2: " ) ;
Serial.println(SerialRead2);
}
if (SerialRead1 == "wheelbase"){
Wheelbase = SerialRead2.toDouble();
}
if (SerialRead1 == "level"){
Level0 = SerialRead2.toDouble();
}
if (SerialRead1 == "gradient"){
Gradient = SerialRead2.toDouble();
}
if (Wheelbase == 1000) {
digitalWrite(LED_BUILTIN, HIGH);
}
else
{
digitalWrite(LED_BUILTIN, LOW);
}
}
Here is my serial outpout:
COM6 - USB-SERIAL CH340 (COM6)
COM6
0
b''
b''
1
b''
b'string1: wheelbase\r\n'
2
b'string2: 1000\r\n'
b'string1: wheelbase\r\n'
3
b'string2: 500\r\n'
b'string1: wheelbase\r\n'
4
b'string2: 1000\r\n'
b'string1: wheelbase\r\n'
5
b'string2: 500\r\n'
b'string1: wheelbase\r\n'
6
b'string2: 1000\r\n'
b'string1: wheelbase\r\n'
7
b'string2: 500\r\n'
b'string1: wheelbase\r\n'
8
b'string2: 1000\r\n'
b'string1: wheelbase\r\n'
9
b'string2: 500\r\n'
b'string1: wheelbase\r\n'
I don't understand why , for i=0 qnd i = 1 the dqtq is not correctly transfered/received.
The LED blink correctly for i = 2 to 9