Interfacing LM35 Temperature Sensor with PIC Microcontroller.

The are many cool sensors available now a days, ranging from IR distance sensor modules, accelerometers, humidity sensors, temperature sensors and many many more(gas sensors, alcohol sensor, motion sensors, touch screens). Many of these are analog in nature. That means they give a voltage output that varies directly (and linearly) with the sensed quantity. For example in LM35 temperature sensor, the output voltage is 10mV per degree centigrade. That means if output is 300mV then the temperature is 30 degrees. In this tutorial we will learn how to interface LM35 temperature sensor with PIC18F4520 microcontroller and display its output on the LCD module.

First I recommend you to go and read the following tutorial as they are the base of this small project.

After reading the ADC tutorial given above you will note the the PIC MCU’s ADC gives us the value between 0-1023 for input voltage of 0 to 5v provided it is configured exactly as in the above tutorial. So if the reading is 0 then input is 0v, if reading is 1023 then input is 5v. So in general form if the adc read out is val then voltage is.

unsigned int val;
val=ADCRead(0); //Read Channel 0
voltage= ((val)/1023.0)*5;

The above formula give voltage in Volts, to get Voltage in mili Volts (mV) we must multiply it with 1000, so

voltage=((val)/1023.0)*5*1000); //Voltage is in mV

since 10mV = 1 degree, to get temperature we must divide it by 10, so

t=((val)/1023.0)*5*100); //t is in degree centigrade

simplifying further we get

t=((val/1023.0)*500);
t=(val*0.48876);

we round off this value, so

t=round(val*0.48876);

remember round() is a standard c library function

Hardware for LM35 based thermometer.

You will need a PIC18F4520 chip running at 20MHz attached with a standard 16×2 LCD Module and LM35 on AN0 pin. LM35 is a 3 pin device as show below.

lm35 temperature sensor pinout

Fig.: LM35 Temperature Sensor Pinout

 

 

connect the +Vs Pin to 5v and GND to GND. The output must be connected to the analog input pin 0 of the PIC18F4520 MCU. It is labeled AN0 in the datasheet. It is pin number 2 on the 40 pin package. It is also called RA0 because it is shared with PORTA0.

We will use our 40 PIN PIC Development board to realize the project. The base board has all the basic circuit to run the PIC. The extra part required for this project like LCD and the LM35 temperature sensor are installed in the expansion board.

LCD Interface with PIC

Fig.: LCD Expansion Board.

The supply for LM35 can be taken from the onboard extra power supply. See the image below.

5v and GND points on PIC Development Board

Fig.: 5v and GND points on PIC Development Board.

Just use single PIN female to female wire to connect with the leads of LM35 temperature sensor. Now plug the LCD Expansion board into the expansion slot and burn the hex file to the board using a PIC ISCP Programmer. Your are now all ready to run.

lm35

Fig.: LM35

C Source Code For PIC Thermometer Project.


/********************************************************************

LM35 Temperature Sensor INTERFACING TEST PROGRAM

---------------------------------------------------------
Simple Program to connect with LM temperature sensor using the
internal ADC of PIC MCU.

The program displays the current environment temperature on
LCD Module.

MCU: PIC18FXXXX Series from Microchip.
Compiler: HI-TECH C Compiler for PIC18 MCUs (http://www.htsoft.com/)

Copyrights 2008-2010 Avinash Gupta
eXtreme Electronics, India

For More Info visit
http://www.eXtremeElectronics.co.in

Mail: me@avinashgupta.com

********************************************************************/
#include <htc.h>

#include <math.h>

#include "lcd.h"

//Chip Settings
__CONFIG(1,0x0200);
__CONFIG(2,0X1E1F);
__CONFIG(3,0X8100);
__CONFIG(4,0X00C1);
__CONFIG(5,0XC00F);


//Simple Delay Routine
void Wait(unsigned int delay)
{
   for(;delay;delay--)
      __delay_us(100);
}

//Function to Initialise the ADC Module
void ADCInit()
{
   //We use default value for +/- Vref

   //VCFG0=0,VCFG1=0
   //That means +Vref = Vdd (5v) and -Vref=GEN

   //Port Configuration
   //We also use default value here too
   //All ANx channels are Analog

   /*
      ADCON2

      *ADC Result Right Justified.
      *Acquisition Time = 2TAD
      *Conversion Clock = 32 Tosc
   */

   ADCON2=0b10001010;
}

//Function to Read given ADC channel (0-13)
unsigned int ADCRead(unsigned char ch)
{
   if(ch>13) return 0;  //Invalid Channel

   ADCON0=0x00;

   ADCON0=(ch<<2);   //Select ADC Channel

   ADON=1;  //switch on the adc module

   GODONE=1;//Start conversion

   while(GODONE); //wait for the conversion to finish

   ADON=0;  //switch off adc

   return ADRES;
}
void main()
{
   //Let the LCD Module start up
   Wait(100);

   //Initialize the LCD Module
   LCDInit(LS_BLINK);

   //Initialize the ADC Module

   ADCInit();

   //Clear the Module
   LCDClear();

   //Write a string at current cursor pos
   LCDWriteString("LM35 Test");
   LCDWriteStringXY(4,1,"Degree Celcius");

   while(1)
   {
      unsigned int val; //ADC Value

      unsigned int t;      //Temperature


      val=ADCRead(0);   //Read Channel 0

      t=round(val*0.48876);//Convert to Degree Celcius

      LCDWriteIntXY(0,1,t,3);//Prit IT!


      Wait(1000);
   }

}


To compile the above code, lcd.c file must be added to the poject. While the lcd.h, myutils.h must be present in the same project folder. More instruction is available in following articles.

Testing The LM35 Based Thermometer.

Turn on the power supply, the screen should show the current temperature readings. Bring a Hot soldering iron tip near the LM35’s pins, don’t touch it keep it 1 or 2mm away. The screen should update with the rising temperature. Now finally touch the pins of LM35 with the tip of iron, the temperature should rise quickly. Keep it there until temperature rise to 80 degrees, then remove the iron. You can now blow some air by your mouth on the sensor to cool it down.

lm 35 temperature sensor demo

Fig.: LM35 Temperature Sensor Demo.

LM35 Temperature Sensor Demo

Fig.: LM35 Temperature Sensor Demo Hardware Setup.

PIC18F4520 based Thermometer using LM35 Schematic

lm35 temperrature sensor demo schematic

PIC18F4520 based Thermometer using LM35 Schematic

General Notes

  • For proper working use the components of exact values as shown above.
  • Wherever possible use new components.
  • Solder everything in a clean way. Major problems arises due to improper soldering,solder jumps and loose joints.
  • Use the exact value crystal shown in schematic.
  • Only burning the HEX file to the MCU is NOT enough. PIC18 devices are fairly complex MCU and can be configured in various ways. Chip is configured using the CONFIG Bytes. Although all hex file given in our site comes with embedded CONFIG bytes. But the user must ensure they are programmed to the chip. Any good programmer has the capability to read the configuration information from the hex file and transfer it to the MCU. Programs will not run without proper configuration byte programming. One major job of configuration is to setup proper oscillator and PLL modes without which the MCU won’t execute a single instruction.
  • To compile the above code you need the HI-TECH C and MPLAB IDE. They must be properly set up and a project with correct settings must be created in order to compile the code. So I request you to read the following articles to become familiar with the built steps.
  • To understand the code you must have good knowledge of core C language. Please don’t be confused with the basic concept of the language.
  • You must be familier with project concept and multi source file concept that used used in most professional languages like C.
  • You need Proteus VSM if you want to develop or debug the project without any hardware setup.

Video

Downloads

By
Avinash Gupta

July 25, 2010

Facing problem with your embedded, electronics or robotics project? We are here to help!
Post a help request.

Avinash

Avinash Gupta is solely focused on free and high quality tutorial to make learning embedded system fun !

More Posts - Website

Follow Me:
FacebookLinkedInGoogle Plus

56 thoughts on “Interfacing LM35 Temperature Sensor with PIC Microcontroller.

  • By electronica - Reply

    Thanks for sharing this project. Sometimes it´s useful conect the output from de LM35 to a OA before the ucontrol

    From Argentina, Cesar

  • By A.M.Das.BSc.Eng.MITE - Reply

    Good attempt.For students really very helpul. In my advice please include all projects Hex files, so one can compare the end results.

    With regards,
    Das

    • By Avinash - Reply

      Hello Mr. Das,

      Thanks a lot for your views. HEX file is available for download at the end of article.

    • By arun - Reply

      sir,i want pic16f877a lm35&real time clock
      program in mikro c .please merge two program(lm35&real timeclock) in single program.
      I NEED YOUR HELP

  • By Jose - Reply

    This is really nice. I think that the temperature sensor you are using is linear. I would be nice to see an example using a thermistor which varies its resistance with respect to temperature.

  • By BoB - Reply

    Hello…

    I’m still a newbie in this field..so, may I ask…this application used PIC 18F4520 to measure the temperature..Is it available if I use PIC 16F877? It has same number of pin
    (40-pin)..Here the question:

    1. What about the crystal value?
    2. What about the programming? What programming is used..?
    3. Is there any change in circuit..?

    From Malaysia,Hasbullah

  • By yawar - Reply

    hi,
    i am using an analog output gas sensor.
    want to transmit the output over a radio link and read it over an LCD.
    anybody has any suggestions please(got a few ideas of my own but quite cumbersome ones)

    thanx

  • By Shobhan - Reply

    only one word..

    “PERFECT”

  • Pingback: Introduction to PIC Interrupts and their Handling in C | eXtreme Electronics

  • Pingback: Anonymous

  • By Ryalzma - Reply

    PIC18F4520 is not available in our country so i’m planning to used PIC18F242. because i only need 3 I/O ports, and it less expensive that PIC18F4520.

    My question is…

    what if i used PIC18F242 instead of PIC18F4520? is there part of the program that i will modify?

    Thank you, and god bless

    • By Avinash - Reply

      @Ryalmza,

      If you like fast result, less frustration, less mess up please use PIC18F4520.
      Porting isn’t for newbies !

  • Pingback: PIC Temperature Sensing System | PyroElectro - News, Projects & Tutorials

  • Pingback: Problem with PIC18F4550 with the LM35

  • By someone - Reply

    THIS IS THE BEST TUTORIAL I HAVE MANAGED TO FIND ON THE WHOLE WEB ……FANTASTIC AND GREAT JOB 🙂

  • By egi - Reply

    how about time response LM35CZ if i used that to measured low temp (under 0 celcius)?because it’s very low time response to measured if i compare with other multimeter

  • By shivendra kumar sahu - Reply

    how can drive relay a particular temp? like >> temp 20 celcius i want drive relay.

  • Pingback: ZigBee Beginner Pls Help - Page 2

  • By MDR SHIVKHUMAR - Reply

    SIR, PL. CHECK IF YOU HAVE THE FOLLOWING 1) PROJECT ON ALL TYPES OF SENSORS. TEMP., HUMIDITY, PRESSURE, 2)PROJECTS ON AUTOMATION 3) PRO. ON TIME DISPLAY, WITH ALARM FOR 7 SEGMENT AND LCD DISPLAY. 4) IR PROJECTS 5) RF BASED TRANSMITTOR , RECEIVER, TRANSCEIVER, CONTROL OF PB IN HOUSE AND SPEED CONTROL OF FAN.
    ETC ETC. I NEED YOUR HELP. WE ARE HAVING “SUPERPRO” MODEL 280U PROGRAMMER.

  • By jerson - Reply

    hola muy interesante este pos, yo estoy trabajando con este sensor, pero lo paso por un amplificador de ganacia 3, como seri ala formula para leerlo en el adc…+gracias

  • By jerson - Reply

    Hello very interesting this post, I’m working with this sensor, but it went through a gain amplifier 3, as would be the formula to read the adc … thanks

  • By Bernard Jackson - Reply

    Please i failed to write a code to read level of oil in transformer and interfacing with microcontroller..!
    anyone who knows please helps me..

  • By gaurav - Reply

    You may also like

    Nokia 3315 LCD based temperature meter
    http://www.circuitvalley.com/2011/11/nokia-3315-lcd-based-temperature-meter.html

  • By prayagsygnet - Reply

    hi, Sir,

    I m 12 std student and learning PIC and microcontroller just now a days. so if possible can u send the program which will work, when temp reaches upper the set point relay will be off and temp reaches down set point the relay should ON. actually its for my hobby circuit.

    thanks sir.

  • By Rakesh - Reply

    Hi Avinash

    I need a help , what will be its behavior if we use PIC81f4550 in place PIC18f4250?
    First of all i wanna show you something,

    I am looking forward to exchange codes.

    Actually i have made a USB Dev Board on PIC18f4550 (http://www.instructables.com/id/USB-Project-USB-Interface-Board-Using-PIC18F455/),which i am controlling with C# applications,the actual tutorial i found enables me to control 2 leds, but i modified the code to enable me use 6 LEDS,for small ROBOTS and project like motor controller (http://www.youtube.com/watch?feature=player_embedded&v=l3BKaztrBWU)

    that is just fine but now

    I am trying to Interface PIC18F4550 with a 16 pin 2X16 LCD module.

    Can u help me with codes.? will this same code work in pic18f4550?

    After the Project gets successful I will provide you all details with pik etc etc 🙂 U can use it here in ur website.

    Looking forward for your reply

    Ron

    http://www.facebook.com/ron.robotics

  • By Rakesh - Reply

    Sorry ,, disregard my last

    I meant PIC18f4550 In place PIC18f4520.

    =======================================
    Hi Avinash

    I need a help , what will be its behavior if we use PIC18f4550 in place PIC18f4520?
    First of all i wanna show you something,

    I am looking forward to exchange codes.

    Actually i have made a USB Dev Board on PIC18f4550 (http://www.instructables.com/id/USB-Project-USB-Interface-Board-Using-PIC18F455/),which i am controlling with C# applications,the actual tutorial i found enables me to control 2 leds, but i modified the code to enable me use 6 LEDS,for small ROBOTS and project like motor controller (http://www.youtube.com/watch?feature=player_embedded&v=l3BKaztrBWU)

    that is just fine but now

    I am trying to Interface PIC18F4550 with a 16 pin 2X16 LCD module.

    Can u help me with codes.? will this same code work in pic18f4550?

    After the Project gets successful I will provide you all details with pik etc etc 🙂 U can use it here in ur website.

    Looking forward for your reply

    Ron

    http://www.facebook.com/ron.robotics

  • Pingback: how to program this code from DS18S20@DS1820 to LM 35..please help me..thank :)

  • By pankaj wagh - Reply

    i need the code for interfacing 18F4520 with lm235 temperature sensore for project

    • By Avinash - Reply

      @pankaj wagh

      Open the IDE and write it !!!

  • By Zetax - Reply

    Hi,

    I’m a new with PIC ; can anyone tell me what the Config bits hex files means ?

    example : __CONFIG(1,0×0200);

    Thanks 🙂

    • By david73 - Reply

      I have a little problem

      __CONFIG(1,0×0200);
      __CONFIG(2,0X1E1F);
      __CONFIG(3,0X8100);
      __CONFIG(4,0X00C1);
      __CONFIG(5,0XC00F);

      __PROG_CONFIG(1,0×0200);
      __PROG_CONFIG(2,0X1E1F);
      __PROG_CONFIG(3,0X8100);
      __PROG_CONFIG(4,0X00C1);
      __PROG_CONFIG(5,0XC00F);

      C:\Users\david\Desktop\LM35Demo_PIC18F4520_20MHz\LM35Demo_PIC18F4520\lcd.p1″ is up to date.
      Executing: “C:\Program Files\HI-TECH Software\PICC-18\9.80\bin\picc18.exe” –pass1 C:\Users\david\Desktop\LM35Demo_PIC18F4520_20MHz\LM35Demo_PIC18F4520\LM35.c -q –chip=18F4520 -P –runtime=default –opt=default -D__DEBUG=1 -g –asmlist “–errformat=Error [%n] %f; %l.%c %s” “–msgformat=Advisory[%n] %s” “–warnformat=Warning [%n] %f; %l.%c %s”
      Warning [356] C:\Users\david\Desktop\LM35Demo_PIC18F4520_20MHz\LM35Demo_PIC18F4520\LM35.c; 109.21 implicit conversion of float to integer
      Executing: “C:\Program Files\HI-TECH Software\PICC-18\9.80\bin\picc18.exe” -oLM35.cof -mLM35.map –summary=default –output=default lcd.p1 LM35.p1 –chip=18F4520 -P –runtime=default –opt=default -D__DEBUG=1 -g –asmlist “–errformat=Error [%n] %f; %l.%c %s” “–msgformat=Advisory[%n] %s” “–warnformat=Warning [%n] %f; %l.%c %s”

  • By kiran - Reply

    This is very useful for us. now, i am doing projects in pic18f67j60 micro controller.i have one doubt, how to interface temperature sensor DS18b20 with pic controller 18f67j60.

    • By Avinash - Reply

      “i am doing projects in pic18f67j60 micro controller.i have one doubt, how to interface temperature sensor DS18b20 with pic controller 18f67j60.”

      This is NOT a doubt this is actually the work you gotta do !

  • By pushpa - Reply

    i want vhdl code for temperature and humidity sensors interfacing to ADC.plz any one can help me to complete the project?

  • By fred - Reply

    hello can you help me, I would like to know how name is the name of the frequency of X1 proteus because I try to look but I did not find.
    thank you in advance;)

  • By Maksat - Reply

    HI !
    This is great tutorial ! thank you very much !
    This project doesn’t show negative temp. Am I right?

    Maksat, from Kazakhstan

  • By shanthini - Reply

    hi,
    i m trying to implement interfacing lm35 with pic18f67j60.how to modify header files in my controller.i m using 64 pin controller.

    thanks

  • By farouk - Reply

    Good day Sir, i really appreciate the work you have done and may God bless you and your family.please i am using 16F877 pic can you send me the .asm file to build? And i also need more explanation on light control using 16F877 also. Am so grateful for your time!

  • By kamal - Reply

    hello sir
    i am using PIC16F877a
    can this source code be applied on it with a little modification?

    • By Avinash - Reply

      @Kamal,

      Yes

      • By Jack -

        how?

      • By Jack -

        can i get a sample of .hex file so i can just load into the pic and test? (PIC16F877A)

      • By abbas -

        i need code for reading temperature from AN0 then sending it to rs232 in mikro c pic?can u help me?

  • By Adison Mhanna - Reply

    hello guys.
    I really get stuck!!!
    I am designing a temperature logger on the PC. I am using LM35 with PIC16F877A microcontroller with its built-in ADC
    I want to send the value of the temperature to the PC using MAX232 to log it somewhere in my database
    I don’t need to display the temperature on an LCD, all I need is to get the value from the LM35 and send it through the RS232 serial port
    I tried so many times with the same wrong result: I am getting values that is always changing even if I am putting a fixed voltage instead of the LM35 sensor.
    I have only one analog input.
    this is the code that I am using:

    #include
    #device adc=10
    #fuses XT,NOLVP,NOWDT,NOPROTECT
    #use delay(clock=4000000)
    #use rs232(baud=9600,xmit=PIN_C6,rcv=PIN_C7)

    float temp;

    void main()
    {
    SETUP_ADC(ADC_CLOCK_INTERNAL);
    SETUP_ADC_PORTS(AN0);
    SET_ADC_CHANNEL(0);
    delay_ms(100);

    while(1) // infinite loop
    {
    temp = read_adc();
    delay_us(100);
    printf(“%2.1f C\n”,temp);
    }
    }

    I think the error is in the VREF settings. Actually I don’t know how to set it and what should I connect to it.
    I’ve already done so many researches in google and in this forum, and I got no answer for my problem. The circuit diagram is the same as the circuits available on the net

    I am getting those values on my PC HyperTerminal while of course the temperature did not changed that way in few seconds !!!
    68.0 C
    44.0 C
    27.0 C
    38.0 C
    89.0 C
    57.0 C
    102.0 C
    77.0 C
    76.0 C
    59.0 C
    68.0 C
    77.0 C
    38.0 C
    38.0 C
    51.0 C
    64.0 C
    44.0 C
    .
    .
    .
    .

    I also tried the “SETUP_ADC_PORTS(A_ANALOG_RA3_RA2_REF);” instead of “SETUP_ADC_PORTS(AN0);”. I wired a 5v to the RA3/AN3/VREF+ and 0v to the RA2/AN2/VREF-
    and i got the same result. but if I put 0v to the RA3/AN3/VREF+, then the result will always be “1023.00 C” as if it is giving the maximum value even when changing

    the input analog value

    please I need a very urgent help in fixing this issue.
    Thank you

  • By aksHAY - Reply

    i WANT TO SEND THESE DIGITAL VALUES OF TEMPERATURE SENSOR TO
    ANOTHER MICRO CONTROLLER USING RF COMMUNICATION. hOW DO i DO THAT. WHAT WOULD BE THE CODE FOR SENDING THOSE DIGITAL VALUES OF THE TEMPERATURE SENSOR SERIALLY TO THE TRANSMITTER AND FORM THERE TO THE ANOTHER MICROCONTROLLER

  • By CASE - Reply

    HI. HOW CAN I MAKE THE PIC DISPLAY THE TEMPERATURE BUT RUN A FAN IF THE TEMPERATURE REACHES A CERTAIN TEMPERATURE? THANK YOU IN ADVANCE

  • By Pratik - Reply

    Here why we divided the ADC output value with 1023 and then multiply with 5 ?

  • By Chetan - Reply

    Hi…
    i am using PIC16F877a
    Plz send me the code for water temperature control by relay using pic microcontroller

  • By mohd raffi - Reply

    hello, before this, i would like to introduce myself. my name is raffi. well, i’m a student from polytechnic. actually i need your help for teaching me how to make a program for interfacing lm35 to pic18f4580. this is for my project (heat extermination).

  • By RAVI - Reply

    Dear Avinash,

    Really great Tutorial by You.

    I am looking for code for displaying value on LCD

    from ADC ( output of ADC Converted to ASCII )

    Thanks in Advance.

    Ravi

  • By Ajay - Reply

    Sir, I am facing a problem with interfacing MQ-7 (Carbon Oxide Gas sensor) with atmega8. Please Help with the Atmel programming.

  • By deepak - Reply

    what i have to do for LM235 temperature sensor

  • By jamil - Reply

    how to program lm35 in assembly when using pic18f4580…Vin=5v

  • By raja - Reply

    Hi bro,

    I guys need help I don’t know how to do programming my ATMega128 … MY subject title TEMPERATURE ALARM (SOUND ALARM AT PRESETTABLE TEMPERATURE) can I get coding for me?

    any 1 know

    • By Avinash - Reply

      @Raja,

      If you don’t know programming then who gave you the task to write the program? And why he/she did so knowing you are not the right person for it?

  • By vadali Srinivasa Rao - Reply

    Sir,
    please suggest when we read below 0 degrees i.e -10 degrees how we can show it in serial monitor.

Leave a Reply

Your email address will not be published. Required fields are marked *


one × 2 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>