Serial printing float variables in a structure

Hi everyone, I have a structure defined like this but when I tried to print the whole structure only char variables gets shown correctly but not the float variables. However, when I tried to print the individual float variables in the structure it gets display correctly. I have attached a SS. ![data|690x162]

struct accel_packet_structure
{
char beetleID = BEETLE_ID ;
char packetID = char(ACCEL_ID);
float accelX;
float accelY;
float accelZ;
char crcResult[3]; //crc
};

//printing individual float variable
Serial.print("accelX = ");
Serial.println(accelPacket.accelX);
Serial.print("accelY = ");
Serial.println(accelPacket.accelY);
Serial.print("accelZ = ");
Serial.println(accelPacket.accelZ);

//print the whole structure
Serial.println((char*)&accelPacket);

There is no way that the compiler knows how to print a structure using the Arduino functions for the Serial Monitor. You have to put that in code yourself.

You could, for example, print the struct as a bunch of hexadecimal values. But then again, you have to write the code for that.

wrap it up in a method and add it to your struct

1 Like
Serial.println((char*)&accelPacket);

What you did with that line is to say "treat the whole struct as a string (array of characters)" which it is not. Some of the fields are characters/strings, so those print ok. But the other fields like floats are stored as 4 bytes encoded in binary, so they make no sense when treated as characters/strings.

Type-casting in C does not take each individual field in a struct and convert it from binary encoding into character encoding. It simply takes the bytes holding the struct and assumes they will all be printable characters.

This is a reason why C language is not ideal for beginners. It assumes the programmer knows what they are doing and does not try to protect them from doing anything crazy. It always gives the programmer "enough rope to hang themselves". But C language is far more efficient than most other languages, so C made it possible to run complex code on very basic processors like atmega328 and attiny45. These processors would not have enough processing power and memory to run other languages like python or java.

@joviyeung in future, please always post code inside code tags, otherwise the forum may corrupt it. Also please do not post images of the serial monitor. Copy the text from serial monitor and paste it into your post, again, between code tags.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.