Lab 9: Temperature Sensors
When correctly powered, this sensor generates a voltage that increases linearly with its temperature and can be read by a microcontroller. Although its pins are not labeled you must take care to hook it up correctly. If you hook up the temperature sensor incorrectly it can get very hot and burn you.
Example Program
Assemble the following circuit and upload the program to your Arduino:
Pay close attention to this diagram. The flat side of the temperature sensor (with the part number barely visible) is facing toward the Arduino. The curved side of the temperature sensor (with no text) is facing away from the Arduino.
void setup()
{
Serial.begin(9600);
pinMode(A0, INPUT);
}
void loop()
{
Serial.println(analogRead(A0));
}
If you open the serial monitor in the Arduino IDE you should see a stream of numbers being printed to it. These are the results of using analogRead() to read the sensor voltage, which encodes the temperature measured by the sensor.
Assignment
Write a program that reads from the temperature sensor and prints the voltage and temperature (in both Celsius and Fahrenheit) to the serial monitor, creating a table of values that puts all three values on a single line of text and looks something like this:
0.24 V | 23.93 °C | 75.07 °F
0.24 V | 23.93 °C | 75.07 °F
0.24 V | 24.41 °C | 75.95 °F
0.24 V | 24.41 °C | 75.95 °F
To convert the values returned by analogRead()
into a voltage, remember that analogRead()
converts a voltage range (0 V to 5 V) into a 10-bit integer (0 to 1023). A value of 45 corresponds to a voltage of 0.22 V.
From there, we can consult the datasheet for the temperature sensor (part number LM35) to see that its voltage starts at 0 V and rises 10 mV (0.01 V) for every degree Celsius above zero. A voltage of 0.22 V corresponds to a temperature of 22 °C.
To convert from Celsius to Fahrenheit, use the following formula:
All this math is a perfect use for variables, which you learned about in the deep dive that followed Lab 2. Because many of these values are not integers, however, you must switch from using int
to float
when declaring all your variables in this lab. This will allow you to store decimal values like 0.22 and 0.01; they will be automatically rounded down to 0 if you use int
instead of float
, which is definitely not what you want!