So, I'm sending a number from python to my arduino using PySerial, and then transferring it back to python and displaying it. Integer numbers work great!
However, when sending a floating point number (number with a decimal), then my zeros get deleted in the conversion process:
10.2 becomes 1.2
230.4 becomes 23.4
203.04 becomes 23.4, etc.
So, since the python program is sending a float (202.023) over serial, I initialized "msg" as a float in the Arduino code. I also changed all instances of '0' to 0.0
Now, sending 202.023 returns 50.000, and sending 12.9 returns 49.005
Any ideas of the problem here?
Here is the updated Arduino code, and thanks for all the help!
How does serial work, exactly? Will PySerial send over a full floating-point number, or send it over digit-by-digit? Also, is the serial connection just a repository, or does it have different channels for when the Arduino writes to it versus when the Python code writes to serial?
float msg = 0.0;
void setup() {
Serial.begin(9600);
}
void loop(){
// While data is sent over serial assign it to the msg
while (Serial.available() > 0){
msg = Serial.read();
}
// see what value is given out
if (msg != 0.0) {
Serial.print(msg);
// Serial.println (msg, HEX);
msg = 0.0;
}
}
Will PySerial send over a full floating-point number, or send it over digit-by-digit?
Unless we have a Python expert here that's what we have to find out. Hence my suggestion to print the incoming bytes in HEX. Either way it will be a few bytes because a float doesn't fit into one.
Just explain why you are confused? Serial.println, by definition, prints on separate lines. Hence each thing printed is on a new line. And when you ask it to print in hex, it does.
You seem to have the impression that Serial.read() reads the whole string sent, and can automatically convert that string to the correct number.
That is not even close to reality. Serial.read() reads one character/byte from the serial port. If you are sending more than one character, you need to read the characters in a loop, until an end of packet marker arrives. Store each character in an array, except the end of packet marker.
When the end of packet marker arrives, use atoi() or atof() to convert the strings to numbers.