I have a tempsensor glued into a beer brewing barrel for measuring temp. The sensor is a TMP35, it came with my arduino kit. I get very unstable readings. It is connected to the analog input pin A0. It's running off of the 5v pin. The arduino is connected via usb. I need help please.
Here is my code. #define RELAY_PIN 3
const int temperaturePin = 0; #define NUMSAMPLES 5
float samples[NUMSAMPLES];
void setup()
{
pinMode(RELAY_PIN, OUTPUT);
Serial.begin(9600); // open serial
}
That's not doing what you think... Look at this as an example of what you need to do:
// take N samples in a row, with a slight delay
average=0;
voltage=0;
for (n=0; n<NUMSAMPLES; n++)
{
voltage += getVoltage(temperaturePin);
delay(10);
}
average = voltage / NUMSAMPLES;
the key to your stability problem is the samples array: you declare samples as an array of 5 floats, but use it as a scalar variable instead. By changing the value of samples, rather than changing the array contents, you are changing the memory location that the array points to. (The more correct explanation is based on "pointer math" which I will jump over to keep the answer short and simple.)
The code I suggested doesn't need an array. The main loop runs often enough, and the temp won't change erratically enough, to store your samples in an array and keep a running average as a filter.
my code recommendation simply takes 5 samples, 10ms apart, in a loop, and then averages them afterwards.
Take a look at this:
Here is my updated code.
#define RELAY_PIN 3
const int temperaturePin = 0;
#define NUMSAMPLES 5
float sumOfSamples;
const int targetTemp = 22; // degrees C
void setup()
{
pinMode(RELAY_PIN, OUTPUT);
Serial.begin(9600); // open serial
sumOfSamples=0.0;
}
void loop()
{
float voltage, degreesC, degreesF;
float average;
sumOfSamples=0.0;
// take N samples in a row, with a slight delay
for (int i=0; i< NUMSAMPLES; i++) {
voltage = getVoltage(temperaturePin);
sumOfSamples += voltage; // create running sum of samples
delay(10); // wait a little to spread out samples to filter measurement noise
}
average = sumOfSamples / NUMSAMPLES;
degreesC = ((average) - 0.5) * 100.0;
degreesF = degreesC * (9.0/5) + 32.0;
Serial.print("voltage: ");
Serial.print(average);
Serial.print(" deg C: ");
Serial.print(degreesC);
Serial.print(" deg F: ");
Serial.println(degreesF);
if (degreesC <= targetTemp) {
Serial.println("Not warm enough");
digitalWrite(RELAY_PIN, HIGH);
}
else {
digitalWrite(RELAY_PIN, LOW);
Serial.println("too hot");
}
delay(500); // wait here before taking another measurement
}
float getVoltage(int pin)
{
return (analogRead(pin) * 0.004882814); // add comment explaining this
}