Reputation: 3661
I am trying to build a small program with arduino using a temperature-sensor.
I thought I knew how to do it but I'm getting some weird outputs.
Here is my code:
int sensorPin = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
int reading = analogRead(sensorPin);
float voltage = reading * 5.0 / 1024;
float temperatureC = (voltage - 0.5) * 100;
Serial.print(temperatureC); Serial.print(" degrees C, ");
Serial.print(voltage); Serial.println(" volts");
delay(1000);
}
This code gives me the output:
-26.56 degrees C, 0.23 volts
-26.56 degrees C, 0.23 volts
-27.05 degrees C, 0.23 volts
-26.56 degrees C, 0.23 volts
-26.07 degrees C, 0.24 volts
-26.07 degrees C, 0.24 volts
Why is it -
in degrees? and Why can I change it to any pin I want and it will still give me a similar output?
Upvotes: 3
Views: 4700
Reputation: 67
First, you have to use the defined symbols A0
int sensorPin = A0;
in the next
float voltage = reading * (5.0 / 1024);
There is an example in File/Examples/Basic/AnalogReadSerial
Upvotes: 0
Reputation: 1539
You are reading this input correctly. In order for you to not get negative degrees, you'll have to process it differently.
With this:
float temperatureC = (voltage - 0.5) * 100;
Any values < 0.5
result in multiplying a negative number by 100.
Try breaking this down using commutative property.
(voltage - 0.5) * 100
is the same as (voltage * 100) - (0.5 * 100)
.(voltage * 100) - 50
. Still, for all values where voltage < 0.5
the temperature will be negative.
temperatureC
by -1
to make it positive and not putting the sensor near anything that is `~ >= 50 degrees Celsius.Also, As jdr5ca pointed out here, you're not actually getting any data from the sensor yet... :(
You are probably getting noise (or garbage) from whatever pin0 is.
EDIT
It is best practice to use parentheses to make order of operations more clear.
float voltage = reading * 5.0 / 1024;
float voltage = reading * (5.0 / 1024);
Upvotes: 3
Reputation: 2819
Analog input 0 is not pin 0.
You should use the defined symbols:
A0,A1,...,A7
for analog inputs.
Try
int sensorPin = A0;
and your program should work.
If you are curious about the actual values, under your Arduino IDE install look in the file
..\hardware\arduino\variants\standard\pins_arduino.h
Upvotes: 4