🛠 Ajouter un capteur I²C (température) sur A4/A5
Objectives
Use the native I²C/TWI bus of the ATmega328P: on the Pro Mini, SDA is on A4 and SCL on A5, on the same row of pins as the analog inputs. The latest SparkFun revision even adds SMD footprints for soldering I²C pull-up resistors — useful for fixed installations, as many modules already include them. We read a MCP9808 temperature sensor (address 0x18) using the Wire library and display the temperature in Celsius.
Hardware
- 1 × Arduino Pro Mini (the I²C bus works identically at 5 V and 3.3 V — power the sensor at the same voltage as the board)
- 1 × I²C sensor module (MCP9808, or LM75/BME280/OLED SSD1306 — same pins)
- 4 × wires: VCC, GND, SDA→A4, SCL→A5
- 4.7 kΩ pull-up resistors to VCC on SDA and SCL if the module does not have them (or solder the ones on the board's footprints)
- FTDI/CP2102 adapter for the serial monitor
Complete Code
// Capteur temperature I2C MCP9808 sur A4 (SDA) / A5 (SCL)
#include <Wire.h>
const uint8_t ADDR = 0x18; // adresse par defaut du MCP9808
void setup {
Serial.begin(57600);
Wire.begin; // maitre I2C, broches A4/A5 fixes sur 328P
if (Wire.requestFrom(ADDR, (uint8_t)1) == 0) {
Serial.println(F("Capteur absent ! Verifier SDA/SCL/adresse"));
}
}
void loop {
Wire.beginTransmission(ADDR);
Wire.write(0x05); // registre ambient temperature
Wire.endTransmission;
Wire.requestFrom(ADDR, (uint8_t)2);
if (Wire.available >= 2) {
int16_t brut = (Wire.read << 8) | Wire.read;
if (brut & 0x8000) brut -= 0x10000; // signe negatif
float t = (brut & 0x0FFF) * 0.0625; // resolution 1/16 degre
Serial.print(F("T = "));
Serial.print(t);
Serial.println(F(" C"));
}
delay(1000);
}
Expected Verification
The serial monitor displays a consistent temperature (~20-25 °C indoors), which rises when you pinch the sensor between your fingers. The presence test in setup displays no errors if SDA/SCL are correctly on A4/A5 and the pull-ups are present. On the latest board revision, the two small footprints near A4/A5 allow soldering 0603 4.7 kΩ resistors for a clean bus in a permanent installation.
Common Errors
- Forgetting the pull-ups on SDA/SCL: the bus remains low, Wire.requestFrom returns 0 bytes; most breakout modules include them, bare chips do not.
- Wiring SDA to A5 and SCL to A4: the ATmega328P has its TWI pins fixed to A4=SDA, A5=SCL, no remapping possible (unlike other MCUs).
- Mixing a 5 V module and a 3.3 V Pro Mini without checking logic levels: the 5 V module can drive SDA above VCC and damage the pin.
- I²C addressing: some modules appear at 0x48 (LM75) instead of 0x18; if there is no response, scan the bus pin by pin.
- Confusing A4/A5 with free analog inputs: once Wire.begin runs, these pins belong to the bus.
Other tutorials for this board
Code examples for this board
clignotante.inoArduinobouton-poussoir.inoArduinopwm-fade.inoArduinocapteur-lumiere-ldr.inoArduinoservo-balayage.inoArduinoruban-neopixel.inoArduino