Listen to this Post
In this guide, we will explore the I2C protocol implementation on a Raspberry Pi 3 using the MCP9808 temperature sensor, leveraging C++17 and the pigpio library.
You Should Know:
1. Enable I2C on Raspberry Pi
Before interfacing with the MCP9808, ensure I2C is enabled on your Raspberry Pi:
sudo raspi-config
Navigate to **Interfacing Options → I2C → Enable**.
Verify I2C detection:
sudo i2cdetect -y 1
If the MCP9808 is connected, its address (usually 0x18) should appear.
#### **2. Install pigpio Library**
The pigpio library allows hardware-level GPIO control. Install it via:
sudo apt-get update sudo apt-get install pigpio
Start the pigpio daemon:
sudo systemctl start pigpiod
#### **3. C++17 Code for MCP9808 Communication**
Here’s a sample code to read temperature from MCP9808:
#include <iostream>
#include <pigpio.h>
#define MCP9808_ADDR 0x18
#define TEMP_REG 0x05
int main() {
if (gpioInitialise() < 0) {
std::cerr << "pigpio initialization failed." << std::endl;
return 1;
}
int handle = i2cOpen(1, MCP9808_ADDR, 0);
if (handle < 0) {
std::cerr << "I2C device not found." << std::endl;
gpioTerminate();
return 1;
}
// Read temperature (2 bytes)
char reg[1] = {TEMP_REG};
i2cWriteDevice(handle, reg, 1);
char data[2];
i2cReadDevice(handle, data, 2);
// Convert to Celsius
int temp_raw = (data[0] << 8) | data[1];
float temp_c = (temp_raw & 0x0FFF) / 16.0;
if (temp_raw & 0x1000) temp_c -= 256;
std::cout << "Temperature: " << temp_c << "°C" << std::endl;
i2cClose(handle);
gpioTerminate();
return 0;
}
#### **4. Compile and Run**
Compile with:
g++ -std=c++17 -o mcp9808_reader mcp9808_reader.cpp -lpigpio -lrt
Run with:
sudo ./mcp9808_reader
### **What Undercode Say**
This implementation demonstrates how to interface with I2C devices using Raspberry Pi and C++17. Key takeaways:
– Always verify I2C device detection (i2cdetect).
– Use pigpio for precise hardware-level control.
– Handle raw sensor data conversion carefully (e.g., MCP9808’s 12-bit temperature).
For further learning:
### **Expected Output:**
Temperature: 24.5°C
References:
Reported By: Chiheb Ameur – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅



