Search code examples
c++arduinospi24-bit

Convert 24 bit 2's Compliment (MSB first) value to a voltage


I have an ADC (AD7767) that I am using to measure a differential signal. The data coming from the ADC is a 2's compliment MSB first 24 bit value. I want to convert this value to a voltage. The reference voltage being used is 5 Volts. I'm using the Arduino IDE. What I have so far is basically this:

const long minValue = 0x800000;
const long maxValue = 0x7FFFFF;
signed long result = 0;
....
long voltage = (result * 0x5) / maxValue;
Serial.println(voltage);

This prints a value of 0.

What the values are:

result = 1010101101010101

0x5: aka Vref

(result * 0x5) = 110101100010101001
(result * 0x5) / maxValue = 0

Solution

  • Yu're trying to store a fraction into a long. The result will always be zero. You need to cast one of the operands to double and store the result in a double.