Thursday, October 25, 2012

Temperature Sensor (DS18S20 + PIC16F877A)

Here's a temperature sensor (thermometer) circuit that you can easily build. It uses the popular PIC 16F877A microcontroller. The temperature sensor is DS18S20. The DS18S20 communicates through the one-wire protocol. The PIC16F877A communicates with the DS18S20 with the one-wire protocol and gets the information for the temperature and displays it on the LCD.

The temperature range of this circuit is -55'C to +125'C.

The methods of communicating with the DS18S20 and sending/receiving commands, and reading the temperature value,  are all explained in the DS18S20 datasheet (datasheets.maximintegrated.com/en/ds/DS18S20.pdf).





Here is the code for the PIC16F877A:
(You can download the source file from: https://rapidshare.com/files/1817975964/DS18S20PIC16F877A.c)
--------------------------------------------------------------------------------------------------------------
//Programmer: Syed Tahmid Mahbub
//Compiler: mikroC PRO for PIC v4.60
//Target PIC: PIC16F877A
--------------------------------------------------------------------------------------------------------------

sbit LCD_RS at RB4_bit;
sbit LCD_EN at RB5_bit;
sbit LCD_D4 at RB0_bit;
sbit LCD_D5 at RB1_bit;
sbit LCD_D6 at RB2_bit;
sbit LCD_D7 at RB3_bit;

sbit LCD_RS_Direction at TRISB4_bit;
sbit LCD_EN_Direction at TRISB5_bit;
sbit LCD_D4_Direction at TRISB0_bit;
sbit LCD_D5_Direction at TRISB1_bit;
sbit LCD_D6_Direction at TRISB2_bit;
sbit LCD_D7_Direction at TRISB3_bit;

unsigned char TempH;
unsigned char TempL;
unsigned char TLow;
unsigned char vDisp[9];
unsigned char DP;

void main() {
     PORTB = 0;
     TRISB = 0;
     LCD_Init();
     LCD_CMD(_LCD_CURSOR_OFF);
     LCD_CMD(_LCD_CLEAR);
     PORTD = 0;
     TRISD = 0x01;
     delay_ms(200); //Wait for sensor and LCD to stabilize
     //vDisp = "+124.5 'C"
     vDisp[4] = '.';
     vDisp[7] = 39; // '
     vDisp[8] = 'C';
     LCD_Out(1,1, "Temp:");
     while (1){
         OW_Reset(&PORTD, 0); // 'Reset command to initialize One-Wire
         OW_Write(&PORTD, 0, 0xCC); // 'Skip ROM Command
         OW_Write(&PORTD, 0, 0x44); // 'Convert_T command
         delay_ms(800); // 'Provide delay for conversion
         RD7_bit = ~RD7_bit;
         OW_Reset(&PORTD, 0); // 'Reset command to initialize One-Wire
         OW_Write(&PORTD, 0, 0xCC); // 'Skip ROM Command
         OW_Write(&PORTD, 0, 0xBE); // 'Read Scratchpad Command
         TempL = OW_Read(&PORTD,0); //Read Temperature low byte
         TempH = OW_Read(&PORTD,0); //Read Temperature high byte
         DP = TempL & 0x01; // 'Check if Temperature is integer or fractional
         if (TempH){ //If reading is negative
            vDisp[0] = '-';
            TempL = ((~TempL) + 1) >> 1;
         }
         else{
             vDisp[0] = '+';
             TempL = TempL >> 1; // 'Shift one position right (divide by 2) to get integer reading and get rid of decimal point
         }
         vDisp[1] = (TempL / 100) + 48; // 'Get hundreds and convert to ASCII
         vDisp[2] = ((TempL / 10) % 10) + 48; // 'Get tens and convert to ASCII
         vDisp[3] = (TempL % 10) + 48; // 'Get units and convert to ASCII
         if (DP){ // 'If reading is fractional, ie has 0.5 at end
            vDisp[5] = '5';
         }
         else{ // 'If reading is a whole number
            vDisp[5] = '0';
         }
         Lcd_Chr(1,8, vDisp[0]);
         Lcd_Chr(1,9, vDisp[1]);
         Lcd_Chr(1,10, vDisp[2]);
         Lcd_Chr(1,11, vDisp[3]);
         Lcd_Chr(1,12, vDisp[4]);
         Lcd_Chr(1,13, vDisp[5]);
         Lcd_Chr(1,14, vDisp[6]);
         Lcd_Chr(1,15, vDisp[7]);
         Lcd_Chr(1,16, vDisp[8]);
     }
}
--------------------------------------------------------------------------------------------------------------
Reference documents:

DS18S20 datasheet: datasheets.maximintegrated.com/en/ds/DS18S20.pdf
PIC16F877A datasheet: ww1.microchip.com/downloads/en/devicedoc/39582b.pdf
mikroC LCD library: http://www.mikroe.com/download/eng/documents/compilers/mikroc/pro/pic/help/lcd_library.htm
mikroC One-Wire library: http://www.mikroe.com/download/eng/documents/compilers/mikroc/pro/pic/help/onewire_library.htm

32 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I have used DS18B20. But the program does not work properly. It shows different temperature. Please give me some suggestion.

    ReplyDelete
  3. The DS18B20 is slightly different from the DS18S20, which is what is used in my circuit.

    For a comparison of the 2 devices, check this out:

    http://www.maximintegrated.com/app-notes/index.mvp/id/4377

    For a circuit/code utilizing DS18B20, check out:

    http://www.edaboard.com/thread279990.html#post1199130

    Regards,
    Tahmid.

    ReplyDelete
  4. hello tahmid , i am using led instead of lcd ,can i use this coding ? if not ,can you give some suggestion regarding the code , ireally need your help , this is for my final year project ,my email : zu_aida87@yahoo.com

    ReplyDelete
    Replies
    1. You need to change the code that handles the display. The LCD code is written for the HD44780 controller. You need to change that to be able to display to an LED display.

      Delete
  5. tahmid brother, i've made a project using 18b20 from ur codes given here.but the problem is that i have added a relay for certain range of temperature.i have used register A for that.the relay is fluctuating. it should be turn on and remain steady.here is my code:
    // LCD module connections
    sbit LCD_RS at RB4_bit;
    sbit LCD_EN at RB5_bit;
    sbit LCD_D4 at RB0_bit;
    sbit LCD_D5 at RB1_bit;
    sbit LCD_D6 at RB2_bit;
    sbit LCD_D7 at RB3_bit;

    sbit LCD_RS_Direction at TRISB4_bit;
    sbit LCD_EN_Direction at TRISB5_bit;
    sbit LCD_D4_Direction at TRISB0_bit;
    sbit LCD_D5_Direction at TRISB1_bit;
    sbit LCD_D6_Direction at TRISB2_bit;
    sbit LCD_D7_Direction at TRISB3_bit;
    // End LCD module connections

    // Set TEMP_RESOLUTION to the corresponding resolution of used DS18x20 sensor:
    // 18S20: 9 (default setting; can be 9,10,11,or 12)
    // 18B20: 12
    const unsigned short TEMP_RESOLUTION = 12;

    char *text = "000.00";
    unsigned temp;

    void Display_Temperature(unsigned int temp2write) {
    const unsigned short RES_SHIFT = TEMP_RESOLUTION - 8;
    unsigned char temp_whole;
    unsigned int temp_fraction;
    PORTA=0;
    TRISA=0;

    // Check if temperature is negative
    if (temp2write & 0x8000) {
    LCD_Chr(2,4,'-');
    temp2write = ~temp2write + 1;
    }
    else{
    LCD_Chr(2,4,' ');
    }

    // Extract temp_whole
    temp_whole = temp2write >> RES_SHIFT ;
    //led blinking
    if(temp_whole>=20 && temp_whole<40)

    {
    porta.f0=1;
    }
    if(temp_whole>=40 && temp_whole<60)
    {
    portd.f1=1;
    }
    if(temp_whole>=60)
    {
    portd.f2=1;
    }

    // Convert temp_whole to characters
    if (temp_whole/100)
    text[0] = temp_whole/100 + 48;
    else
    text[0] = '0';

    text[1] = (temp_whole/10)%10 + 48; // Extract tens digit
    text[2] = temp_whole%10 + 48; // Extract ones digit

    // Extract temp_fraction and convert it to unsigned int
    temp_fraction = temp2write << (4-RES_SHIFT);
    temp_fraction &= 0x000F;
    temp_fraction *= 625;

    // Convert temp_fraction to characters
    text[4] = temp_fraction/1000 + 48; // Extract thousands digit
    text[5] = (temp_fraction/100)%10 + 48; // Extract hundreds digit


    // Print temperature on LCD
    Lcd_Out(2, 5, text);

    }

    void main() {
    ADCON1=0x06;

    Lcd_Init(); // Initialize LCD
    Lcd_Cmd(_LCD_CLEAR); // Clear LCD
    Lcd_Cmd(_LCD_CURSOR_OFF); // Turn cursor off
    Lcd_Out(1, 1, " Temperature: ");
    // Print degree character, 'C' for Centigrades
    Lcd_Chr(2,11,223); // Different LCD displays have different char code for degree
    // If you see greek alpha letter try typing 178 instead of 223

    Lcd_Chr(2,12,'C');

    //--- Main loop
    do {
    //--- Perform temperature reading
    Ow_Reset(&PORTE, 2); // Onewire reset signal
    Ow_Write(&PORTE, 2, 0xCC); // Issue command SKIP_ROM
    Ow_Write(&PORTE, 2, 0x44); // Issue command CONVERT_T
    Delay_us(120);

    Ow_Reset(&PORTE, 2);
    Ow_Write(&PORTE, 2, 0xCC); // Issue command SKIP_ROM
    Ow_Write(&PORTE, 2, 0xBE); // Issue command READ_SCRATCHPAD

    temp = Ow_Read(&PORTE, 2);
    temp = (Ow_Read(&PORTE, 2) << 8) + temp;

    //--- Format and display result on Lcd
    Display_Temperature(temp);

    Delay_ms(500);
    } while (1);
    }

    ReplyDelete
  6. Dear Tahmid,,

    it 's good project..,,,can you post the code using hitech compiler

    ReplyDelete
  7. Hello all !!! Masud Al Hasan -> your problem in code (led blinking) is caused by TRISA & PORTA . This command must to be out of ,, void Display_Temperature(unsigned int temp2write) " , at the begining of code. Good luck ;)

    ReplyDelete
  8. hello, i need DS1822 codes to connect it with pic16f877a some help please

    ReplyDelete
  9. Dear Tahmid,
    If I using DS18S20 to detect the temperature and i want it (the temperature) shows visual basic in my PC . can I get some help and suggestion please my email : claralavita52@gmail.com
    thank you

    ReplyDelete
  10. i really likes your blog and You have shared the whole concept really well. and Very beautifully
    บาคาร่าออนไลน์
    gclubwritten,
    soulful read! thanks for sharing.
    GCLUB มือถือ

    ReplyDelete
  11. hi dear its blog very nice and helpful thanks from inverter

    ReplyDelete
  12. Hello .

    Your ds18s20 code is good work just protues . But when i work real hardware not working. Why not work what's problem can you help me this code.

    ReplyDelete
  13. Hello .

    Your ds18s20 code is good work just protues . But when i work real hardware not working. Why not work what's problem can you help me this code.

    ReplyDelete
  14. Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative.
    mcafee.com/activate|
    norton.com/setup|
    mcafee.com/activate|
    norton.com/setup|
    office.com/setup
    office.com/setup

    ReplyDelete
  15. office.com/setup – Check out the easy steps for installing, downloading, activation and re-installing the Microsoft office at www.office.com/setup. MS Office Products like Office 365 Home, Office 2016 Business Premium, Office Professional 2016, Renew your Office, Office 365 Personal etc.

    ReplyDelete
  16. Sign in to enter office setup product key. Know how to benefit, download, install, set in movement, uninstall and reinstall MS office setup.
    office.com/setup
    http://officecom-officeoffice.com/
    call us at +1-888-421-9666[tool free]

    ReplyDelete
  17. Sign in to enter office setup product key. Know how to benefit, download, install, set in movement, uninstall and reinstall MS office setup.
    office.com/setup
    http://officecom-officeoffice.com/
    call us at +1-888-421-9666[tool free]

    ReplyDelete
  18. Microsoft office setup is the product setup record with this setup document you can introduce on your PC and a portion of the bolstered gadget to utilize Microsoft office. if you are looking for www.office.com/setup ? here we provide the ms world setup and we also provide office product key activation. For more info www.webroot.com/safe

    ReplyDelete
  19. While some businesses may be hesitant about shifting to cloud, Office 365 does have several essential features and advantages. Workers are already adept at working on Office applications, by getting Office 365 and activating the setup ms office-setup your business not just gets the chance to utilize the safe efficiency programming which it has been utilizing for a considerable length of time, yet you can likewise give the obligation on tech giant Microsoft. for more detail visit to our website
    www.office.com/setup
    www.norton.com/setup
    www.norton.com/setup

    ReplyDelete
  20. norton.com/setup have the total arrangement of elements which can ensure your advanced on the web and disconnected existence of the registering gadgets norton.com/setup it help you to secure it as well as it can keep up the strength of your PC, increment the speed with inbuilt PC Optimization device. In the event that you just obtained Norton Retail Card from the store or online please visit norton.com/setup into your web program to reclaim and enact your Norton Security item on the web. norton.com/setup

    ReplyDelete
  21. This is an informative blog. Keep it up. I am looking forward to this kind of blog. Thanks for sharing it with us norton.com/setup

    www.norton.com/setup

    ReplyDelete
  22. Thank you for sharing this blog, It is an amazing blog, I am really impressed by your blog, It’s really useful norton.com/setup
    www.norton.com/setup

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. Thank you for sharing this blog, It is an amazing blog, I am really impressed by your blog, It’s really useful www.avg.com/retail

    avg.com/retail

    www.avg.com/activate

    avg.com/activate

    ReplyDelete
  25. There are many blogs I have read But when I read Your Blogs I have found such useful information, fresh content with such amazing editing everything is superb in your blog, Thank you so much for sharing this useful and informative information with us. Wish you all the best for upcoming comments. And I have also few informative links which I am going share here. wwww.norton.com/setup enter product key
    www.norton.com/setup, Norton product key, Norton Setup, norton.com/setup

    ReplyDelete
  26. Nice post, you give the clear idea of the topic and I subscribed your blog
    Buy xanax online

    ReplyDelete
  27. It is a great blog post. I am Always reading your blog. Helpful and Informative blog. Thanks for sharing this information with us.
    espn.com/activate
    www.espn.com/activate


    ReplyDelete
  28. Let’s face it, in today’s current economic climate, particularly when you consider current events for the last 18 months or so, finding employment is tough. It doesn’t matter whether you’re looking for a job to help you stay on top of your bills, or if you’ve decided that you want to forge a new career path, a well-written and professional resume will drastically increase your chances of obtaining employment. So find resume writing services here

    ReplyDelete
  29. I am very grateful to Dr Dawn Acuna, for bringing back my husband who left me for another woman, that moment my husband Left me I thought I lost everything until a friend of my gave me Dr Dawn Acuna, WhatsApp contact, I messaged her and told her the pain I was going through so she told me that everything was going to be fine that if I have the faith and believe in her that the spell will surely work for me and my husband will surely come back home and she told me what to do, so those things were done and 48 hrs later my husband came back home begging for my forgiveness, am so happy and grateful to Dr Dawn Acuna, if you need her help contact her, she's accurate and sincere,
    * If you want spell to conceive.
    *If you want to get pregnant.
    * If you want to return your lover
    *If you want to cure any kind of sickness
    * If you need spell to get good job. *If you want to stop having miscarriage. And E.T.C. write her on email { dawnacuna314@gmail.com }
    WhatsApp: +2348032246310

    ReplyDelete
  30. All thanks to Mr Anderson for helping with my profits and making my fifth withdrawal possible. I'm here to share an amazing life changing opportunity with you. its called Bitcoin / Forex trading options. it is a highly lucrative business which can earn you as much as $2,570 in a week from an initial investment of just $200. I am living proof of this great business opportunity. If anyone is interested in trading on bitcoin or any cryptocurrency and want a successful trade without losing notify Mr Anderson now.Whatsapp: (+447883246472)
    Email: tdameritrade077@gmail.com

    ReplyDelete
  31. Çdo problem ka një zgjidhje kur takoni personin e duhur! Mos kini frikë se ekziston një magjistar i shkëlqyer dhe zgjidhës shpirtëror i problemeve që është në gjendje t'i japë fund problemit tuaj. Dua te vleresoj Dr Fady qe me riktheu martesen time me magjine e saj, Pas 1 viti ndarje me burrin tim, me ndihmen e magjistares se mrekullueshme Dr Fady burri im erdhi ne shtepi dhe tani jemi te lumtur bashke per mire, edhe nje here faleminderit per Dr Fady gjithashtu shëroi të gjitha llojet e sëmundjeve si p.sh.

    1 DEKLARATË DASHURI
    2 WIN S EX KTHIMI
    3 FRUTA GOMS
    4 NJOFTIM PËR PROMOCION
    5 DEKLARATA E MBROJTJES.
    6 MAGJIA E BIZNESIT.
    7 DEKLARATË E MIRË PUNËS.
    8 HIV SIDA.
    9 NDALO MISKARRIMIN.
    10 MIROOD NJOFTIM SHPALLJE.
    11 SHKAK I TELEKINEZËS.
    DREJTSHKRIMI I LOTARIVE DHE ÇËSHTJA GJYQËSORE Kontakt Kontaktoni atë për ndihmën tuaj nëpërmjet: drfady720@gmail.com
    WHATSAPP:+2349039422406

    ReplyDelete