I am trying to transfert float data between a PC (python) and a teensy 4.1.
Python code :
import numpy as np
import serial
data = np.array([1,0.5]).astype(np.float32) #this is test data, my real data is a lot bigger
S = serial.Serial(port='COM17', baudrate=9600, timeout=1)
S.write(data.tobytes())
x=S.read(8)
transferring data in binary between systems can be difficult, e.g. different data lengths, endianness, number representation, etc
although transferring data in binary is more efficient and accurate it may be simpler initially to transfer the data as text, e.g. comma seperated floats such as 1.0,0.5,3.14159, 2.718281828, etc etc - once you have the system working look at binary again
also avoid uploading fragments of code it makes it difficult to understand and debug - upload complete programs (if the program is very large implement a simple test program which shows the problem)
also may be worth asking on the Python forum for help
ran the following python code on a Win10 PC
it transmits bytes of binary data and then displays text received
import numpy as np
import serial
data = np.array([1,0.5,3.14159, 2.718281828]).astype(np.float32) #this is test data, my real data is a lot bigger
print(data)
S = serial.Serial(port='COM6', baudrate=115200, timeout=1)
S.write(data.tobytes())
print(data.tobytes())
#x=S.read(8)
print("reading serial");
while 1:
try:
# serial data received? if so read byte and print it
while S.in_waiting > 0:
char = S.read()
print(str(char,'ASCII'),end='')
except:
pass
ran following code on an ESP32
it receives 8 bytes of data, copies the bytes into float variables and displays the results
EDITED: to use a float array for results
void setup() {
Serial.begin(115200);
while (!Serial.available())
;
byte buffer[100];
int len = Serial.readBytes(buffer, 100);
Serial.print(len);
Serial.print(" bytes received "); for (int i = 0; i < len; i++) {
Serial.print(" 0x");
Serial.print(buffer[i], HEX);
}
Serial.println();
Serial.print("sizeof(float) ");
Serial.println(sizeof(float));
// copy bytes into float variables and display
float data[10];
memcpy(data, buffer, len);
Serial.print("data = ");
for (int i = 0; i < len / sizeof(float); i++) {
Serial.print(" ");
Serial.print(data[i]);
}
}
void loop() {}