DISPLAYING TEMPERATURE IN PYTHON USING ARDUINO AND TEMPERATURE SENSOR LM35

Photo of author

By Jackson Taylor

Home » Electronics Topics » Python & OpenCv » DISPLAYING TEMPERATURE IN PYTHON USING ARDUINO AND TEMPERATURE SENSOR LM35

As an Amazon Associate we earn from qualifying purchases.

An Arduino can read an LM35 temperature sensor, and Python can show the result on your computer. The Arduino measures the temperature and sends it over USB as serial data. A short Python script, using the pyserial library, reads that data and prints it. This guide covers the wiring, the Arduino sketch, the Python script and the common problems you may hit.

The video below shows the project working.

What you need

How the LM35 works

The LM35 is an analog sensor. Its output voltage rises by 10 mV for every degree Celsius, so a reading of 250 mV means about 25 °C. It needs no calibration for basic use, which makes it a good first sensor. If you are still choosing a part, our guide to the best temperature sensor for Arduino projects compares the common options.

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video

Wiring the LM35 to the Arduino

Hold the LM35 with the flat face towards you and the pins pointing down. Then connect the pins from left to right:

  1. Pin 1 (+Vs): to the Arduino 5V pin
  2. Pin 2 (Vout): to analog pin A0
  3. Pin 3 (GND): to GND

Check the pin order against the datasheet for your exact package. Reversing the power pins can damage the sensor.

Arduino code

The sketch reads A0 once per second and sends the value over the serial port at 9600 baud.

void setup()
{
  Serial.begin(9600);  delay(100);
}
void loop()
{
  int sensorValue = analogRead(A0)/2;
  delay(1000);
  Serial.println(sensorValue);
}

Why divide by 2?

The Arduino Uno has a 10-bit analog-to-digital converter. With the default 5 V reference, it turns 0 to 5 V into values from 0 to 1023, so each step is about 4.9 mV. Since the LM35 gives 10 mV per °C, each step is roughly 0.49 °C. Dividing the raw value by 2 therefore gives the temperature in °C as a whole number, close to the true value.

See also
PIC16F877A-HITECH C-Digital Output & Input

For better accuracy, use floating-point maths instead:

float tempC = analogRead(A0) * 5.0 * 100.0 / 1024.0;

This is the same calculation without the shortcut. On boards with a 1.1 V internal reference, such as the Uno, you can call analogReference(INTERNAL) for finer resolution. That only works for temperatures up to roughly 100 °C, and the formula changes to use 1.1 instead of 5.0.

Note that Serial.println() sends the number followed by a carriage return (0x0d) and a line feed (0x0a). That line ending is how the Python side knows where each reading stops.

Python code

The original script for this project was written for Python 2. It reads one byte at a time and treats the carriage return (0x0d) as the end of a reading:

import serial
                     """download library file from
                     https://pypi.python.org/pypi/pyserial """
                     temp='0';
                     ser = serial.Serial(port='com2',baudrate=9600)
                                    #enter comport name,baud rate
                     ser.close()              #closes previously open serial port
                     ser.open()                   # opens serial port
                     x = ser.read()#reads a byte of the data .
                     while x == chr(0x0d):
                         x = ser.read()
                     while True:
                         x = ser.read()#reads a byte of the data .
                         if x == chr(0x0d):
                             x = ser.read()
                             print 'temperature is',temp, ' n'
                             temp='0';
                         else:
                             temp=temp + x
                     #enter ctrl+c for closing this infinite loop

This will not run on Python 3. The print statement is a function there, and ser.read() returns bytes, so comparing it with chr(0x0d) never matches. Here is a simpler Python 3 version that reads a whole line at a time:

import time
import serial

# Change the port name to match your Arduino
# (for example COM3 on Windows or /dev/ttyACM0 on Linux)
ser = serial.Serial(port='COM2', baudrate=9600, timeout=2)
time.sleep(2)  # the Arduino resets when the port opens

try:
    while True:
        line = ser.readline().decode('ascii', errors='ignore').strip()
        if line:
            print('Temperature is', line, 'C')
except KeyboardInterrupt:
    pass  # press Ctrl+C to stop
finally:
    ser.close()

The script opens the port, waits two seconds for the Arduino to restart, then reads one line per loop. It decodes the bytes to text, strips the line ending and prints the value. Press Ctrl+C to stop it, and the port closes cleanly.

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works
See also
HIGH VOLTAGE BUCK CONVERTER USING ARDUINO (275V DC TO 165V DC)

Running the project

  1. Upload the Arduino sketch from the Arduino IDE.
  2. Find the port name in the IDE under Tools > Port.
  3. Close the Serial Monitor. Only one program can use the port at a time.
  4. Put that port name in the Python script and run it.
  5. Touch the sensor or warm it gently and watch the printed value rise.

If you only want to read a temperature sensor with Arduino and view the values in the Serial Monitor, you can skip the Python part. Python becomes useful once you want to log, process or chart the data.

Troubleshooting

  • Port error or access denied: the Serial Monitor or another program is holding the port, or the port name is wrong.
  • No output: check that both sides use 9600 baud and that the sketch uploaded without errors.
  • Strange or jumping values: check the wiring and make sure the sensor shares a common ground with the board. Long wires can add noise, so keep them short. Averaging a few readings also helps.
  • Readings that are too high: the sensor may be heating up from the board or your fingers, so give it a moment to settle.
  • Syntax error on the print line: you are running the Python 2 script on Python 3. Use the second version above.

Where to go next

Once the readings reach Python, you can save them to a file, draw a live graph, or plot the readings online with a service like ThingSpeak. If you want to learn more about the serial side, see how to send serial data in Python in both directions. For a different microcontroller, there is an example of the LM35 with an MSP430 as well.

FAQ

Can I use the LM35 with Python without an Arduino?

Not directly. The LM35 gives an analog voltage, and a normal computer has no analog input. The Arduino converts the voltage to a digital number and passes it on.

See also
IF - STATEMENT IN PYTHON

Why does the Arduino code divide the reading by 2?

With a 5 V reference and a 10-bit converter, each step is about 0.49 °C. Dividing by 2 gives a rough temperature in whole degrees Celsius. The float formula is more precise.

Which COM port should I use?

Use the port that the Arduino IDE shows for your board. On Windows it looks like COM3, and on Linux or macOS it looks like /dev/ttyACM0 or /dev/tty.usbmodem. The ‘com2’ in the original script was only an example.

Does this work with Python 3?

Yes, with the updated script above. The original script uses Python 2 syntax and needs changes to run on Python 3.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works