I have three thermistors for reading temperatures. I wanna make a function which I would call for
every thermistor, so I don't need to copy the same code three times.
I wrote a function with one parameter to determine which analog port I would like to read but it doesn't work.
Temperature is the same as first reading for all three (temp2 and temp3 are the same as temp1).
What am I doing wrong?
void loop
{
temp1 = getTemp(1);
temp2 = getTemp(2);
temp3 = getTemp(3);
}
int getTemp(byte pin)
{
int adc;
if (pin == 1) adc = analogRead(A0);
else if (pin == 2) adc = analogRead(A1);
else if (pin == 3) adc = analogRead(A2);
return adc;
}
What is the interval between reading two different analog pins? Not very much. Typically, you would read the pin twice, and throw away the first reading. The second will be meaningful. The first may not, actually reflecting what the device connected to the other pin did with the ADC.
In my test code I originally had Serial.prints between the reads, so when PaulS made his suggestion I moved them all to after all the reads. Still works OK for me.
//forum thread 450847
int temp1;
int temp2;
int temp3;
void setup()
{
Serial.begin(9600);
Serial.println("setup");
Serial.println(" ");
}
void loop()
{
Serial.println("loop");
temp1 = getTemp(1);
temp2 = getTemp(2);
temp3 = getTemp(3);
Serial.print(temp1);
Serial.print(" ");
Serial.print(temp2);
Serial.print(" ");
Serial.println(temp3);
Serial.println("");
delay(1000);
}
int getTemp(byte pin)
{
int adc;
if (pin == 1) adc = analogRead(A0);
else if (pin == 2) adc = analogRead(A1);
else if (pin == 3) adc = analogRead(A2);
return adc;
}
It works now. The problem was that I was also filtering the values in the same function, but some variables have been local. When first one came in, it has set the values for another temperatures.
I can read analog values in a function now but I can't filter them in a function. I still need to filter them separated for three times.
I can read analog values in a function now but I can't filter them in a function.
Why not? There is nothing you can do in one function (loop()) that you can't do in another (user-defined) function, if the function is written correctly.
PaulS:
Why not? There is nothing you can do in one function (loop()) that you can't do in another (user-defined) function, if the function is written correctly.
I will keep that in mind.
I am filtering with millis() timer and flag, so separate variable for timer and flag for every temperature. I know how to do this in three separated functions but not in a single one (yet).