Convert a voltage stored in a float to a byte

Hey guys,

I've been working on a project that uses LoRaWAN and TTN to control some outdoor devices periodically.

I've written a website to control everything and I'm pretty much all done but there's one last thing I'm unsure of...

To send the smallest amount of data possible via LoRaWAN I'm sending my battery voltage within one byte, and my hardware runs off a 12V SLA so the voltage usually sits around say 13.2V.

I've written my website so it takes the byte, and for example 132, would be displayed as 13.2V. Anything below 100 (10V) is just considered completely flat, and a value of 255 would be very concerning for a 12V SLA. So I think this system is pretty acceptable? I'm just using the first two decimal digits of the byte for the 13V and the last digit for the .2.

So the website handles the data fine but I'm unsure of how to do it on the Arduino.

I have a float x = 12.2 and want to somehow convert that to byte x = 122.

Any tips would be appreciated,

Thanks.

How about

float x = 12.2;
byte byteVolts = x * 10;
1 Like

Congratulations, you (re-)invented the fixed point type!

Calculation already demonstrated by @groundFungus.

You already proved that all your values are within the byte range, no problems so far :slight_smile:

1 Like

It's that easy. :grin:

Thanks!

RHS side is actually 122 or 122.0? If it is 122.0, then will 122 (the integer part) be automatically assigned to byte-type variable byteVolts or do we need to cast like the following?

float x = 12.2;
x = x*10.0;     //both operands are of same type
byte byteVolts = (byte)x;    //taking out the integer part
Serial.print(byteVolts);   //shows: 122

you might consider if you need that float to be a float at all?

just shift the decimal where ever you read the data in (presumable an analog read of a voltage divider?)

byteVolts = analogRead(vPin) * 10;

i dont know what your actual code looks like, but you get the idea...

Almost certainly not!

The output of an ADC is not a float, so scaling it should not be a problem.

And note that you almost certainly do not need to convert the ADC reading to Volts before sending it - just subtract the count of the minimum anticipated voltage, sent the residual number and add it back and "decimalise" it at the other end. :+1:

The value depends on the ADC reference voltage and bit count so that a conversion is highly recommended!

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