We define a variable called voltage, of the float data type, and a variable called tempPin, of the integer type; we will set the latter to represent pin 0 of Arduino. In order to make our PC communicate with Arduino using serial communication, we need to set the data rate in terms of bits per second. So, we will call the Serial.begin function to set the serial data transmission speed to 9,600 bits per second (however, it can be any baud rate).
Within the loop function, we will invoke the analogRead function to read the value from the specified analog pin, 0. Recall that the Arduino boards contain a multichannel, 10-bit analog to digital converter that maps input voltages between 0 and the operating voltage (5V or 3.3V) into integer values between 0 and 1023. The value read from the analog pin, 0, is assigned to the voltage variable.
We are using a 5V Arduino and an LM35 sensor is already connected to its analog pin. We will use the following formula to convert the 10-bit analog reading into a temperature:
Voltage at pin in milliVolts = Reading from ADC * 5000/1024
This formula converts the numbers 0-1023 from the ADC into 0-5000 mV. To convert millivolts retrieved from this formula into temperature, we will use another formula:
Centigrade temperature = Analog voltage in mV / 10
The two previously mentioned formulas can be rewritten as follows:
Centigrade temperature = Reading from ADC * 0.48828125;
Using this formula, the value read into the voltage variable is converted into temperature in Celsius and is assigned to the tempInCelsius variable. To convert temperature in Celsius (°C) into Fahrenheit (°F), the following formula is used:
F=(C*9)/5+32
Using this formula, the temperature in Celsius found in the tempInCelsius variable is converted into Fahrenheit and assigned to the tempinFahrenheit variable.
Temperatures in °C and °F are displayed to the serial port by invoking. The temperature reading can be seen by opening the serial monitor. Press Ctrl + Shift + M to open the serial monitor and display the temperature. You can also press the LM35 sensors in your thumbs to see the rise and fall in temperature.
We will introduce a delay of 1,000 milliseconds between every temperature display by invoking the delay function. That is, the application will keep displaying the temperature in °C and °F infinitely with a delay of 1,000 milliseconds in between.
After uploading the program to Arduino, we can press Ctrl + Shift + M to open the serial monitor. In the serial monitor, we will get the temperature in Celsius as well as in Fahrenheit. You will keep getting a temperature reading continuously with a delay of 1,000 milliseconds in between:
In the following photograph, you can see the LM35 sensor attached to the Arduino board. You can press the LM35 sensor in your thumbs to see the rise in the temperature readings:
Voilà! We've successfully created a temperature sensor with an LM35 sensor using Arduino.