Created
July 28, 2021 03:02
-
-
Save bungernut/6b05b82fa8e29fa5ec706acb8cc9733b to your computer and use it in GitHub Desktop.
Modbus float32 to uint16_t conversion for registers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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