Realize data transmission between single-chip microcomputer and host computer by skillfully using union

Recently, I am learning the data transmission between the arduino single-chip microcomputer and the host computer. The temperature and humidity information is measured by the temperature and humidity sensor and then sent to the host computer program for storage through the serial port. For the float type, using Serial.print(float)the function can be conveniently displayed on the serial monitor, but it also destroys the data structure, and using the Serial.write(char[])function needs to convert float to char[], and using the union union can save the tedious conversion process.
The definition format of the union is:

union 共用体名{
    
    
    成员列表1
    成员列表2...;
    成员列表n;
};

The difference between a structure and a union is that each member of a structure occupies different memory and has no influence on each other; while all members of a union occupy the same memory, modifying one member will affect all other members.
The memory occupied by the structure is greater than or equal to the sum of the memory occupied by all members (there may be gaps between members), and the memory occupied by the union is equal to the memory occupied by the longest member. The union uses the memory overlay technology, which can only save the value of one member at a time. If a new member is assigned a value, the value of the original member will be overwritten.

Arduino terminal program:

union SeFrame
{
    
    
  float Float;
  char Char[4];
};
SeFrame TEMP;

void setup() {
    
    
  Serial.begin(9600);
}

void loop() {
    
    
  
  delay(2000);
  
  float t = 26.125;
  TEMP.Float=t;
  Serial.write(TEMP.Char,4);
}

PC conversion function:

float RecFloat(char *a)  //a为接收到的char数组
{
    
    
  union
  {
    
    
    float Float;
    char Char[4];
  }recFloat;
  memcpy(recFloat.Char,a,4);
  return recFloat.Float;
}

Guess you like

Origin blog.csdn.net/YiBYiH/article/details/116214969