Skip to content

Instantly share code, notes, and snippets.

@bungernut
Created July 28, 2021 03:02
Show Gist options
  • Save bungernut/6b05b82fa8e29fa5ec706acb8cc9733b to your computer and use it in GitHub Desktop.
Save bungernut/6b05b82fa8e29fa5ec706acb8cc9733b to your computer and use it in GitHub Desktop.
Modbus float32 to uint16_t conversion for registers
/*
Figuring out how to convert floats to uint16_t for Modbus and vice-versa
Serial Output:
Float 3.14 = [16456 , 62915]
[ 5243 , 16830 ] = 23.76
*/
#include <Arduino.h>
float f = 3.14;
uint16_t a[2] = {16830, 5243};
void setup() {
Serial.begin(115200);
}
union {
float asFloat;
uint16_t asInt[2];
} flreg;
void loop() {
Serial.print("Float "); Serial.print(f); Serial.print(" = ");
flreg.asFloat = f;
Serial.print("["); Serial.print(flreg.asInt[1]);
Serial.print(" , ");
Serial.print(flreg.asInt[0]); Serial.println("]");
flreg.asInt[1] = 16830;
flreg.asInt[0] = 5243;
Serial.print("[ "); Serial.print(flreg.asInt[0]); Serial.print(" , ");
Serial.print(flreg.asInt[1]); Serial.print(" ]");
Serial.print(" = "); Serial.println(flreg.asFloat);
delay(10000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment