i have made a project that a python script communicates with arduino sending various data types. Well everything works great except when arduino sends back floats in some cases.
For e.g: When arduino sends numbers 4112.5, -7631.5 python receive them correct In case of 4112.112, -7631.23 python receives 4112.11181641, -7631.22998047
What is causing this??
Python code: https://drive.google.com/file/d/1uKBTUW319oTh6YyZU9tOQYa3jXrUvZVF/view
import os
import struct
import serial
import time
print('HELLO WORLD!!!!\nI AM PYTHON READY TO TALK WITH ARDUINO\nINSERT
PASSWORD PLEASE.')
ser=serial.Serial("COM5", 9600) #Serial port COM5, baudrate=9600
ser.close()
ser.open() #open Serial Port
a = int(raw_input("Enter number: ")) #integer object
b = int(raw_input("Enter number: ")) #integer object
c = float(raw_input("Enter number: ")) #float object
d = float(raw_input("Enter number: ")) #float object
time.sleep(2) #wait
ser.write(struct.pack("2i2f",a,b,c,d)) #write to port all all number bytes
if a == 22 :
if b == -22 :
if c == 2212.113 :
if d == -3131.111 :
print("Congratulations!!! Check the ledpin should be ON!!!")
receivedbytes=ser.read(16) #read from Serial port 16 bytes=2 int32_t + 2
floats from arduino
(number1,number2,number3,number4,)=struct.unpack("2i2f",receivedbytes)
#convert bytes to numbers
print "Arduino also send me back
",str(number1),",",str(number2),",",str(number3),",",str(number4)
else :
print("WRONG PASSWORD")
os.system("pause") #wait for user to press enter
Arduino code:https://drive.google.com/file/d/1ifZx-0PGtex-M4tu7KTsIjWSjLqxMvMz/view
struct sendata { //data to send
volatile int32_t a=53;
volatile int32_t b=-2121;
volatile float c=4112.5;
volatile float d=-7631.5;
};
struct receive { //data to receive
volatile int32_t a; //it will not work with int
volatile int32_t b;
volatile float c;
volatile float d;
};
struct receive bytes;
struct sendata values;
const int total_bytes=16; //total bytes to send
int i;
byte buf[total_bytes]; //each received Serial byte saved into byte array
void setup() {
Serial.begin(9600);
pinMode(13,OUTPUT); //Arduino Mega ledpin
}
void loop() {
}
void serialEvent() { //Called each time Serial data is received
if (Serial.available()==total_bytes){ //Receive data first saved
toSerial
buffer,Serial.available return how many bytes are saved.The Serial buffer
space is limited.
while(i<=total_bytes-1){
buf[i] = Serial.read(); //Save each byte from Serial buffer to
byte
array
i++;
}
memmove(&bytes,buf,sizeof(bytes)); //Move each single byte memory
location of array to memory field of the struct,the numbers are
reconstructed
from bytes.
if (bytes.a==22){ //Access each struct number.
if (bytes.b==-22){
if (bytes.c==2212.113){
if (bytes.d==-3131.111){ //If the password is right
Serial.write((const uint8_t*)&values,sizeof(values));
//Write
struct to Serial port.
delay(100);
digitalWrite(13,HIGH);//Turn ON LED.
}
}
}
}
}
}
For further information you can also check my video: