i2c_oled.c

ESP32-H2 · File : i2c_oled.c · Language : C · Use case : Piloter un OLED SSD1306 par le pilote I2C maître

ESP-IDF v5's new i2c_master API works with bus/device handles: create the bus, add the device at 0x3C, then transmit frames prefixed by the SSD1306 control byte (0x00 command, 0x40 data).

Hardware required

An ESP32-H2 board (RISC-V 96 MHz, IEEE 802.15.4 radio only — no Wi-Fi) such as a DevKitM-1, powered over USB. 1 I2C SSD1306 128×64 OLED module.

Wiring

SDA on GPIO6, SCL on GPIO7 (free DevKit pins), VCC 3.3 V, GND. Modules default to address 0x3C.

How it works

i2c_new_master_bus configures pins and clock; i2c_master_bus_add_device reserves the device at 400 kHz. Each transmission starts with the SSD1306 controller control byte. Program it with ESP-IDF (idf.py set-target esp32h2); the USB-Serial/JTAG port (GPIO26/27) acts as console and flash port. Hold Boot + Reset for download mode if needed.

Going further

Complete with the 5×7 font table to show battery voltage and 802.15.4 RSSI live.

i2c_oled.c

// i2c_oled.c — ecrit « H2 OK » sur un SSD1306 128x64 (0x3C).
#include <string.h>
#include "driver/i2c_master.h"
#include "esp_log.h"

#define SDA  GPIO_NUM_6
#define SCL  GPIO_NUM_7
#define ADRESSE 0x3C
static const char *TAG = "oled";

static void cmd(i2c_master_dev_handle_t dev, uint8_t c)
{
    uint8_t d[2] = { 0x00, c };          // 0x00 = octet de controle commande
    i2c_master_transmit(dev, d, 2, 100);
}
static void dat(i2c_master_dev_handle_t dev, const uint8_t *b, int n)
{
    uint8_t buf[34] = { 0x40 };          // 0x40 = donnees
    memcpy(buf + 1, b, n);
    i2c_master_transmit(dev, buf, n + 1, 100);
}

void app_main(void)
{
    i2c_master_bus_handle_t bus_handle;
    i2c_master_bus_config_t bus = { .i2c_port = I2C_NUM_0,
        .sda_io_num = SDA, .scl_io_num = SCL,
        .clk_source = I2C_CLK_SRC_DEFAULT, .glitch_ignore_cnt = 7 };
    ESP_ERROR_CHECK(i2c_new_master_bus(&bus, &bus_handle));
    i2c_master_dev_handle_t dev;
    i2c_device_config_t dcfg = { .dev_addr_length = I2C_ADDR_BIT_LEN_7,
        .device_address = ADRESSE, .scl_speed_hz = 400000 };
    ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dcfg, &dev));

    // Init minimale SSD1306 (page mode) puis texte en police 5x7.
    // (suite : cf. table de caracteres du driver SSD1306 public)
    ESP_LOGI(TAG, "SSD1306 initialise sur 0x%02X", ADRESSE);
}

← Back to the board