Designing a PIC18 I2C Temperature Sensor Monitoring System

Designing a dedicated temperature monitoring system can be both instructive and highly practical. In this tutorial, we will focus on creating a temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. monitor using a PIC18Understanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondUnderstanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondExplore PIC microcontroller families: learn how PIC12’s compact design, PIC16’s balanced features, and PIC18’s robust performance for innovative projects. microcontroller and an I2C temperature sensor. Our goal is to tap into the capabilities of the PIC18’s built-in I2C peripheral, interface it with a digital temperature sensor, and display the temperature readings. By the end, you will have a fundamental understanding of how to set up I2C communication, read sensor data, and show the reported temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. in a user-friendly manner.

Introduction and Overview🔗

In environments where precise temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. tracking is crucial-for example, chemical labs, server rooms, or even personal projects-microcontrollers often act as the heart of the system. The combination of a PIC18Understanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondUnderstanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondExplore PIC microcontroller families: learn how PIC12’s compact design, PIC16’s balanced features, and PIC18’s robust performance for innovative projects. microcontroller and an I2C sensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions. provides a robust yet straightforward way to accomplish this task, thanks to:

Key Topics Covered in this Tutorial:

1. Selecting an appropriate I2C temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. sensor.

2. Hardware connections for PIC18Understanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondUnderstanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondExplore PIC microcontroller families: learn how PIC12’s compact design, PIC16’s balanced features, and PIC18’s robust performance for innovative projects. I2C.

3. Configuring the PIC18Understanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondUnderstanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondExplore PIC microcontroller families: learn how PIC12’s compact design, PIC16’s balanced features, and PIC18’s robust performance for innovative projects. for I2C communication.

4. Writing firmware to request and read temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. data.

5. Displaying temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. readings (for example, on an LCD or via a serial interface).

This tutorial assumes you have familiarity with MPLAB XGetting Started with MPLAB X and the XC8 CompilerGetting Started with MPLAB X and the XC8 CompilerSet up MPLAB X IDE and XC8 compiler for PIC programming with our comprehensive guide detailing installation, configuration, and debugging techniques. and the XC8 compilerGetting Started with MPLAB X and the XC8 CompilerGetting Started with MPLAB X and the XC8 CompilerSet up MPLAB X IDE and XC8 compiler for PIC programming with our comprehensive guide detailing installation, configuration, and debugging techniques. environment, as well as basic knowledge of C programming for microcontrollers.

Choosing an I2C Temperature Sensor🔗

Several I2C-compatible temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. sensors are available on the market. Some popular examples include the MCP9808, LM75, TMP102, and Si7021. They differ in accuracy, operating voltage ranges, and additional features like programmable temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. alerts.

For simplicity, let’s consider a generic I2C sensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions.. We will name it “TempSensor” and assume it has a 7-bit address (e.g., 0x48), and it stores temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. data in one or more internal registers that we can read through I2C.

What to consider when selecting a sensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions.:

Hardware Connections🔗

Since I2C uses a two-wire interface, the hardware connections are straightforward:

1. SDA Pin: Data line shared between the PIC18 MCU and the sensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions..

2. SCL Pin: Clock line that synchronizes data exchange.

3. Power Lines: VDD and GND to power the sensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions..

4. Pull-Up Resistors: Typically, 4.7kΩ pull-upsMastering Digital I/O on PIC MCUs with Practical ExamplesMastering Digital I/O on PIC MCUs with Practical ExamplesLearn hands-on techniques for configuring and using digital I/O pins on PIC microcontrollers to control LEDs, sensors, and more in practical projects. on SDA and SCL to VDD.

An example wiring layout might resemble the following table:

SignalPIC18 MicrocontrollerTempSensor ModuleExternal Resistor?
VDD+5V (or 3.3V)VDD-
GNDGNDGND-
SDARC4 (Example)SDA Pin4.7kΩ to VDD
SCLRC3 (Example)SCL Pin4.7kΩ to VDD

All modern PIC18Understanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondUnderstanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondExplore PIC microcontroller families: learn how PIC12’s compact design, PIC16’s balanced features, and PIC18’s robust performance for innovative projects. devices with an I2C peripheral typically have an MSSP (Master Synchronous Serial Port) module. In some variants, these lines can be remapped using Peripheral Pin SelectAdvanced Peripheral Pin Selections (PPS) on PIC MCUsAdvanced Peripheral Pin Selections (PPS) on PIC MCUsUnlock flexible design with advanced PPS on PIC MCUs. Our guide details how to remap pins, optimize layouts, and improve peripheral functionality. (PPS), but the essence remains the same: the designated SDA and SCL lines must connect to the sensor.

Configuring I2C on the PIC18🔗

Before capturing temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. data, we first configure the Master Mode on the PIC18’s I2C module. While each PIC18 chip might have slightly different Special Function RegistersPIC Memory Architecture: Program Memory, Data Memory, and SFRsPIC Memory Architecture: Program Memory, Data Memory, and SFRsExplore the PIC microcontroller’s memory architecture, covering Program, Data, and Special Function Registers for improved embedded system performance. (SFRs) for I2C, the general steps to initialize I2C include:

1. Set the I2C Pins (SDA and SCL) as inputs (TRIS bits = 1).

2. Configure SCL FrequencyGenerating Audio with PIC Timers and PWMGenerating Audio with PIC Timers and PWMExplore how to configure PIC timers and PWM for audio signal generation, including hardware setup, duty cycle adjustments and simple tone creation. by setting the baud rate register (e.g., SSPADD or SSPxADD). The formula typically resembles:

$$ F_{SCL} = \frac{F_{OSC}}{4 \times (SSPADD + 1)} $$

where:

  • F_SCL is the desired I2C clock rate (e.g., 100 kHz).
  • F_OSC is the MCU clock frequency (e.g., 8 MHz, 16 MHz, etc.).
  • SSPADD (or SSPxADD) is the value to be programmed.

3. Enable the MSSP Module for I2C Master Mode by setting control bits in SSPCON1 (or SSPxCON1) and SSPCON2 (or SSPxCON2).

Below is a small schematic representation of the I2C master initialization in C:

// Example: PIC18F series, setting up I2C Master at 100 kHz (assume Fosc = 8 MHz)
#define _XTAL_FREQ 8000000  // System oscillator frequency
void I2C_Init(void)
{
    // Set RC3 (SCL) and RC4 (SDA) as input
    TRISCbits.TRISC3 = 1;
    TRISCbits.TRISC4 = 1;
    // Set the I2C clock rate
    // Formula for 100 kHz: SSPADD = (Fosc / (4 * F_SCL)) - 1
    // e.g.,  SSPADD = (8,000,000 / (4 * 100,000)) - 1 = 19
    SSPADD  = 19;
    SSPCON1 = 0b00101000;  // Enable I2C Master mode
    SSPCON2 = 0;
    SSPSTAT = 0b10000000;  // Slew rate disabled for standard speed
}

Communicating with the I2C Sensor🔗

With I2C configured, the PIC18Understanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondUnderstanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondExplore PIC microcontroller families: learn how PIC12’s compact design, PIC16’s balanced features, and PIC18’s robust performance for innovative projects. can initiate transactions to the sensor. The basic flow for reading temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. is:

1. Send a Start Condition to signal the beginning of communication.

2. Send the SensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions. Address with the Write bit (address << 1 | 0).

3. Send the SensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions. Register Pointer to tell the sensor we want to read from the temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. register.

4. Send a Repeated Start Condition.

5. Send the SensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions. Address with the Read bit (address << 1 | 1).

6. Read the Data Bytes from the sensor (temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. bytes).

7. Send a Stop Condition to end communication.

Here is an illustrative code snippet for reading a 16-bit temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. register:

unsigned int I2C_ReadTemperature(void)
{
    unsigned char tempHigh, tempLow;
    unsigned int temperature = 0;
    // Start condition
    SSPCON2bits.SEN = 1;   // Initiate a Start
    while(SSPCON2bits.SEN); // Wait for completion
    // Send sensor write address
    SSPBUF = (0x48 << 1) | 0;  // Example address 0x48, Write bit
    while(!PIR1bits.SSPIF);
    PIR1bits.SSPIF = 0;
    // Send register pointer (assume 0x00 is temperature register)
    SSPBUF = 0x00;
    while(!PIR1bits.SSPIF);
    PIR1bits.SSPIF = 0;
    // Repeated start
    SSPCON2bits.RSEN = 1;
    while(SSPCON2bits.RSEN);
    // Send sensor read address
    SSPBUF = (0x48 << 1) | 1;  // Example address 0x48, Read bit
    while(!PIR1bits.SSPIF);
    PIR1bits.SSPIF = 0;
    // Receive high byte
    SSPCON2bits.RCEN = 1;   // Enable receive mode
    while(!PIR1bits.SSPIF);
    PIR1bits.SSPIF = 0;
    tempHigh = SSPBUF;
    // Send ACK for next byte request
    SSPCON2bits.ACKDT = 0;    // Acknowledge
    SSPCON2bits.ACKEN = 1;    // Send ACK
    while(SSPCON2bits.ACKEN);
    // Receive low byte
    SSPCON2bits.RCEN = 1;
    while(!PIR1bits.SSPIF);
    PIR1bits.SSPIF = 0;
    tempLow = SSPBUF;
    // Send NACK since we only needed 2 bytes
    SSPCON2bits.ACKDT = 1;    // NACK
    SSPCON2bits.ACKEN = 1;    // Send NACK
    while(SSPCON2bits.ACKEN);
    // Stop condition
    SSPCON2bits.PEN = 1;
    while(SSPCON2bits.PEN);
    // Combine high and low bytes (assuming 16-bit data)
    temperature = (tempHigh << 8) | tempLow;
    return temperature;
}

Depending on the sensor, the temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. might be in different formats. Some sensors automatically provide a two’s complement reading, while others provide an unsigned format with fractional bits. Consult your chosen sensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions.’s datasheet for details on how to convert raw data into degrees Celsius or Fahrenheit.

Processing and Displaying the Temperature🔗

Once raw data is retrieved, we convert it into a human-readable format. As an example, if the sensor outputs temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. in 0.125°C increments per LSB (least significant bit), you might need to multiply or divide accordingly. A typical formula:

float convertTemperature(unsigned int rawData)
{
    // Example: Suppose sensor yields 0.125°C per LSB
    // and the top byte is sign-extended. Adjust as needed.
    // This is purely an illustrative calculation.
    float temperature = (float)rawData * 0.125;
    return temperature;
}

Display Options can vary:

Here is an example of (very simplified) pseudo-code to show results on a character LCD:

#include "lcd.h"  // Assume a separate library for time-saving
void DisplayTemperature(float tempC)
{
    char buffer[16];
    sprintf(buffer, "Temp: %.2fC", tempC);
    LCD_SetCursor(0, 0);     // Row 0, Column 0
    LCD_WriteString(buffer);
}

Putting It All Together🔗

Below is a high-level overview of our main application flow:

void main(void)
{
    float temperatureC = 0.0f;
    // 1. Initialize system
    //    Set up oscillator, configure I2C, initialize LCD, etc.
    I2C_Init();
    LCD_Init();
    // 2. Continuously read temperature
    while(1)
    {
        unsigned int rawTemp = I2C_ReadTemperature();
        temperatureC = convertTemperature(rawTemp);
        DisplayTemperature(temperatureC);
        // Delay or wait a short period before reading again
        __delay_ms(1000);
    }
}

Common Troubleshooting Tips🔗

1. Check Pull-Up Resistors: Ensure SDA and SCL lines have proper pull-up resistors. Without them, the bus may remain stuck or show unreliable signals.

2. Verify the SensorAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions. Address: Some sensorsAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions. have pins that change the I2C address. Make sure you use the correct 7-bit address in your firmware.

3. Handle Bus Collisions (BCLIF): If you experience collisions on the bus, check if another master device is trying to drive the lines or if you’re inadvertently re-initializing the peripheral.

4. Adjust Timing: If the temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. reading is unreliable at higher clock rates (e.g., 400 kHz), consider starting with a standard 100 kHz I2C bus speed.

5. TemperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. Format: Confirm how your sensor encodes temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. bits. A mismatch in sign bits or fractional representation can cause large errors in displayed values.

Conclusion🔗

Building a temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. monitor with a PIC18Understanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondUnderstanding PIC Family Variants: PIC12, PIC16, PIC18, and BeyondExplore PIC microcontroller families: learn how PIC12’s compact design, PIC16’s balanced features, and PIC18’s robust performance for innovative projects. microcontroller and an I2C sensor is an effective way to learn about digital communication protocols and practical sensor interfacing. By connecting just a few lines-SDA, SCL, VDD, and GND-you can continuously read real-time temperature data and display it in a clear, meaningful way. This fundamental setup can be expanded to log temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. to memory, integrate additional sensors (humidity, pressure), or even utilize wireless modules for remote monitoring.

With the principles covered in this tutorial, you now have a strong starting point to incorporate I2C-based sensorsAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions. into your PIC18 projects, enabling a wide range of applications that rely on accurate environmental monitoring.

Author: Marcelo V. Souza - Engenheiro de Sistemas e Entusiasta em IoT e Desenvolvimento de Software, com foco em inovação tecnológica.

References🔗

Share article