I have a piece of code that i think should be working right but it dont seem to be. When i run the code it just prints the same float value over and over it dont actually change or seem to be averaging anything. where am i going wrong? Also i am using an esp8266
unsigned long now2=0;
struct packet {
int local;
float temp;
};
packet localData;
if (millis() - now2 >= 1000) {
averageReading ();
now2 = millis();
}
void averageReading () {
float sum = 0.0 ;
for (byte i = 0 ; i < 10 ; i++) {
sum += sensors.getTempFByIndex(0); //get temp reading from dallas library
}
Serial.println("okay");
localData.temp = sum / 10 ;
Serial.print(localData.temp);
Serial.println("ºF");
}
Here is a whole program that compiles,
#include <OneWire.h>
#include <DallasTemperature.h>
unsigned long now2 = 0;
const int oneWireBus = 4;
struct packet {
int local;
float temp;
};
packet localData;
OneWire oneWire(oneWireBus);
DallasTemperature sensors(&oneWire);
void setup()
{
Serial.begin(115200);
}
void loop()
{
if (millis() - now2 >= 1000) {
averageReading ();
now2 = millis();
}
}
void averageReading () {
float sum = 0.0 ;
for (byte i = 0 ; i < 10 ; i++) {
sum += sensors.getTempFByIndex(0); //get temp reading from dallas library
}
Serial.println("okay");
localData.temp = sum / 10 ;
Serial.print(localData.temp);
Serial.println("ºF");
}
reading the value without the averaging works.
Delta_G:
How long does it take to read the sensor? Will it let you read in rapid succession like that? How much do you expect the temperature to actually change i that time?
i'm not sure. i figured i could read the sensor at least 10 times a second. i'm trying to record the high and low temperature in a 24 hours period. The problem i'm facing is sometimes i might get a invalid reading that is -160 and this updates my minimum reading with the bad reading. It don't seem to happen very often. if the recording readings were off by a few degrees thats okay. but by a few hundred is not okay.
I slowed down the millis loop to 8 seconds and changed the average to only take 5 readings and the problem is the same. the strange part is it always seems to print 67.78 as the value no matter if the sensor is 100+ degrees.
I figured it out, i forgot to add "sensors.requestTemperatures();"my mistake thank you