I’m trying to send lots of float data from python to arduino. But when I check the values, some of them are wrong.
the part of python code:
arduino = serial.Serial(port=args.port, baudrate=115200, timeout=5000)
print(feature[0:50])
# Send each float in a feature
for num in feature:
arduino.write(bytes(str("%f" % num), "ascii") + bytes("n", "ascii"))
# Receive the input back
recv_features = []
for _ in range(len(feature)):
recv = arduino.read_until()
recv_features.append(float(recv.decode(encoding="ascii")))
print(recv_features[0:50])
where feature
is a list with 1440 floats.
the arduino code:
#define INPUT_LEN 10
char X_test_byteArr[INPUT_LEN];
float data[1440];
void setup() {
Serial.begin(115200);
Serial.setTimeout(5000);
}
void loop() {
size_t num_read;
// Receive every input as string, convert to float
while (Serial.available()==0) {}
for (int i = 0; i < 1440; i++) {
// Wait for input data
while (Serial.available()==0) {}
// Read input string
num_read = Serial.readBytesUntil('n', X_test_byteArr, INPUT_LEN);
X_test_byteArr[num_read] = '';
// Convert input string to float
data[i] = float(atof(X_test_byteArr));
}
for (int i = 0; i < 1440; ++i) {
Serial.println(data[i]);
}
}
Here is the sent data:
[-1.12, 0.32, -0.48, -0.84, 3.01,
0.03, -0.80, 0.23, -0.69, 1.02,
0.55, 0.24, -0.13, -0.55, -1.42,
4.20, 0.05, 0.04, 0.29, -0.45,
-0.12, 0.21, -0.81, -0.07, 1.03,
-0.09, -0.01, 0.38, -0.99, 1.59,
0.21, -0.18, 0.03, 0.39, 1.38,
0.76, -0.15, -0.25, 0.23, -0.02,
0.00, -0.48, -0.27, 0.19, -0.09,
-1.77, 0.24, -0.52, -0.08, 0.43]
and the received data in python:
[-1.12, 0.32, -0.48, -0.84, 3.01,
0.03, -0.80, 0.23, -0.69, 1.02,
0.55, 0.24, -0.13, -0.55, -1.42,
4.20, 0.05, 0.04, 0.29, -0.45,
-0.12, 0.21, -0.81, -0.07, 1.03,
-0.09, -0.01, 37987, 0.00, -0.99,
59294, 0.21, -0.18, 0.03, 0.39,
1.38, 0.76, 0.00, -0.15, -0.25,
22918, 0.00, -0.02, 0.00, -0.48,
-0.27, 19308, -0.09, -1.77, 0.24]
I guess add some delay can fix it, but any better method can speed up the whole progress? Thanks for any idea.
New contributor