I'm working on some code to read the supply battery's voltage level from an analog input pin. Vin supplies input to a voltage divider circuit, which is then connected to an analog input of the MCU. I am using preprocessor definitions rather than constants because I would like to keep static memory use to a minimum, though out of desperation I did try a version of my code using constants with the same results.
Here is a simple test sketch which illustrates the problems I am experiencing:
#include "WProgram.h"
#define BATT_R1 220000.0
#define BATT_R2 100000.0
#define BATT_VOUT 5.0 * 1000000.0
#define BATT_VIN BATT_VOUT / (BATT_R2 / (BATT_R1 + BATT_R2))
#define BATT_STEPS 1024.0
#define BATT_STEP BATT_VIN / BATT_STEPS
#define BATT_ADJUST 100000.0 / BATT_STEP
void setup()
{
Serial.begin(9600);
Serial.println("---- Begin ----");
Serial.print("BATT_R1: ");
Serial.println(BATT_R1);
Serial.print("BATT_R2: ");
Serial.println(BATT_R2);
Serial.print("BATT_VOUT: ");
Serial.println(BATT_VOUT);
Serial.print("BATT_VIN: ");
Serial.println(BATT_VIN);
Serial.print("BATT_STEPS: ");
Serial.println(BATT_STEPS);
Serial.print("BATT_STEP: ");
Serial.println(BATT_STEP);
Serial.print("BATT_ADJUST: ");
Serial.println(BATT_ADJUST);
Serial.println("---- End ----");
}
void loop()
{
}
And the output from that sketch:
---- Begin ----
BATT_R1: 220000.00
BATT_R2: 100000.00
BATT_VOUT: 5000000.00
BATT_VIN: 16000000.00
BATT_STEPS: 1024.00
BATT_STEP: 15625.00
BATT_ADJUST: 62500000.00
---- End ----
The portion that is calculated incorrectly is the BATT_ADJUST definition. The value should be 6.4. Also notice that all my definitions supply numbers in floating point values. More of the calculations are skewed when I provide integral values. I have tried casting these values to type float or unsigned long and the results are exactly the same. I also find this very strange since, even casting to an integral value, the println() method still displays BATT_ADJUST as if it were a floating point value, defaulting to 2 decimal places. I'm fairly certain that the Arduino is being reprogrammed since it responds appropriately when I reprogram it with additional calls to the print method, or with an entirely different sketch.
I am using an official Arduino Mega 2560. I write most of the code in Vim, but am programming the board with Arduino software version 0022 under Mac OS X 10.6. In case you are wondering, I am aware that the Arduino software must reload the sketch if any code has been altered outside the ide.
Any assistance would be greatly appreciated.