I am using a very simple calculation to try to build a temperature sensor and the math is coming out completely wrong. I try it on a calculator and the "apple" variable is the issue (I used this to be sure I was not using a keyword). For one, I am getting a negative where no negative number should exist. I am posting the part of the program that deals with the serial printing and I am including below that the results I keep getting. It also seems to matter where I put the parentheses. Help?!?!
Exploring Arduino, Second Edition
Code Listing 3-2: Temperature Alert Sketch
// Temperature Alert!
const int BLED=9; // Blue LED Cathode on Pin 9
const int GLED=10; // Green LED Cathode on Pin 10
const int RLED=11; // Red LED Cathode on Pin 11
const int TEMP=0; // Temp Sensor is on pin A0
const int LOWER_BOUND=139; // Lower Threshold
const int UPPER_BOUND=147; // Upper Threshold
int val=0; // Variable to hold analog reading
float tempC;
float apple;
float tempF;
void setup()
{
pinMode (BLED, OUTPUT); // Set Blue LED as Output
pinMode (GLED, OUTPUT); // Set Green LED as Output
pinMode (RLED, OUTPUT); // Set Red LED as Output
Serial.begin(9600);
}
First multiplication of the apple expression, val*5000, will be calculated as int. As maximum value of the int type in the arduino mcu is 32768, the calculation will overflow and the result will be incorrect
try this:
Seems to be a common error. If you had broken up the complex calculation into individual steps and printed the results of each step you would have discovered the source of the error.
Change at least one of the constant values in each step to be a float by making, perhaps 5000 to be 5000.0. same for each of the remaining steps. All calculations are done as integers with integer results unless you tell the compiler the intermediate results are also floats.