Jeg_1
April 5, 2017, 4:32pm
1
Hi people. I'd like to ask about the following sketch which utilizes a temperature sensor. First float variable named temperatureC is being assigned by the value getTemperatureC(). Shouldn't this value has to be connected somehow with the readings from pin A0? Where in the program this happens? I was waiting something like
Float getTemperatureC()
getTemperature C()=analogread(kPinTemp) or something. What is your opinion?
SKETCH
const int kPinTemp= A0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
float temperatureC= getTemperatureC();
Serial.print(temperatureC);
Serial.println("degreesC");
delay(500);
}
float getTemperatureC()
{
int reading = analogRead(kPinTemp);
float voltage= (reading* 5.0)/1024;
return(voltage-0.5)* 100;
}
float convertToF(float temperatureC)
{
return(temperatureC*9.0 /5.0)+ 32.0;
}
Always use code tags to post code, so that it looks like this:
int reading = analogRead(kPinTemp);
which, incidentally, answers your question "Shouldn't this value has to be connected somehow with the readings from pin A0?"
In order to understand a program, you have to read every line, and figure out what that line is doing.
Jeg_1
April 5, 2017, 5:19pm
3
Thanks jremington. I still don't see a connection between "getTemperatureC" value and "reading" variable. I need more reading. Thanks anyway
getTemperatureC is a function. As you read down loop:
float temperatureC= getTemperatureC();
This means that the computer will immediately jump to the getTemperatureC() function and start executing:
int reading = analogRead(kPinTemp);
Then it will do some calculations:
float voltage= (reading* 5.0)/1024;
return(voltage-0.5)* 100;
the "return" statement means that the program will put the value (voltage - 0.5) * 100 as the return from getTemperatureC and continue from there.
I don't know any other way to explain it to you.
Jeg_1
April 5, 2017, 5:51pm
5
You explained it perfect. I had missed the part that it was a function. Thanks a lot!
@Jeg_1
Firtly, your codes, as jremington has suggested, should be like this (Step-3):
Now, look for your expected relation by reading the codes line-by-line.
The Sketch
const int kPinTemp= A0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
float temperatureC= getTemperatureC();
Serial.print(temperatureC);
Serial.println("degreesC");
delay(500);
}
float getTemperatureC()
{
int reading = analogRead(kPinTemp);
float voltage= (reading* 5.0)/1024;
return(voltage-0.5)* 100;
}
float convertToF(float temperatureC)
{
return(temperatureC*9.0 /5.0)+ 32.0;
}