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() {}
python console displays
======================= RESTART: C:\Python311\SERIAL1.PY =======================
[1. 0.5 3.14159 2.7182817]
b'\x00\x00\x80?\x00\x00\x00?\xd0\x0fI@T\xf8-@'
reading serial
16 bytes received 0x0 0x0 0x80 0x3F 0x0 0x0 0x0 0x3F 0xD0 0xF 0x49 0x40 0x54 0xF8 0x2D 0x40
sizeof(float) 4
data = 1.00 0.50 3.14 2.72
binary data received OK and float values 1.0 and 0.5 are correct