Try Embedded

Nucleo-F401RE: I2C OLED

Drive a 128×64 SSD1306 OLED with your own I2C1 driver on PB8 and PB9: start, address, data and stop, register by register.

Displays · Intermediate

In a real product: Fitness band display (Wearables): A small OLED shows time and stats.

The Nucleo's I2C pins are D14 (SDA) and D15 (SCL), at the top of the header. On the chip they are PB9 and PB8, the pins of I2C1. With no library at hand, this program writes the I2C driver and the display driver itself, so you can see every step of a transfer.

What you'll learn

  • Setting pins to open-drain alternate function (AF4) for I2C, and I2C1's clock registers (CR2, CCR, TRISE)
  • One I2C write, flag by flag: START → SB, the address → ADDR, each byte → TXE, then BTF → STOP
  • How an SSD1306 is set up with commands, and how its 1 KB of pixels is sent as pages of 8 rows

How it works

CR2's FREQ tells I2C1 its APB1 clock in MHz (16). For 100 kHz standard mode, CCR is 16 MHz / (2 × 100 kHz) = 80, and TRISE is the clock in MHz plus one. I2C lines are pulled up and only ever pulled low, so the pins are open-drain.

i2c_write() sets START and waits for SB, sends the display's address (0x3C) shifted left with the write bit, waits for ADDR, and reads SR2 to clear it. Each byte goes into DR when TXE says it is empty. After the last one it waits for BTF, so the byte has really gone out, and sets STOP.

The SSD1306 takes a control byte first: 0x00 for commands, 0x40 for pixel data. Each byte of data is a column of 8 pixels, its lowest bit on top, and 128 columns make a page; 8 pages fill the screen. The program draws into a frame buffer in RAM, with a small 5×7 font for its text, and sends the whole buffer each frame.

Try this

  • Set CCR for 400 kHz fast mode (FS and DUTY in CCR) and see the frame rate go up.
  • Put a logic analyzer on D14 and D15 and decode one command.
  • Add the letters you need to the font and print your name.

main.c

// Bare-metal C on the Nucleo-F401RE: no Arduino core and no HAL. CMSIS names every register.
// A 128x64 SSD1306 OLED on I2C1 (PB8 SCL = D15, PB9 SDA = D14, address 0x3C): a title, the uptime and a bouncing ball.
#include <stdio.h>
#include <string.h>
#include "stm32f4xx.h"

#define OLED 0x3C

static volatile uint32_t ticks;   // milliseconds since SysTick started
static uint8_t frame[1 + 128 * 8];   // the data control byte (0x40), then the 8 pages of pixels
static uint8_t *const pixels = frame + 1;

void SysTick_Handler(void) {
  ticks++;
}

int __io_putchar(int ch) {
  while (!(USART2->SR & USART_SR_TXE)) {}
  USART2->DR = ch;
  return ch;
}

// One I2C write: start, the address with the write bit, the bytes, stop.
static void i2c_write(uint8_t addr, const uint8_t *data, unsigned len) {
  I2C1->CR1 |= I2C_CR1_START;
  while (!(I2C1->SR1 & I2C_SR1_SB)) {}
  I2C1->DR = addr << 1;
  while (!(I2C1->SR1 & I2C_SR1_ADDR)) {}
  (void)I2C1->SR2;   // reading SR2 after SR1 clears ADDR
  for (unsigned i = 0; i < len; i++) {
    while (!(I2C1->SR1 & I2C_SR1_TXE)) {}
    I2C1->DR = data[i];
  }
  while (!(I2C1->SR1 & I2C_SR1_BTF)) {}
  I2C1->CR1 |= I2C_CR1_STOP;
}

static const uint8_t SETUP[] = {
  0x00,               // control byte: commands follow
  0xAE,               // display off
  0xD5, 0x80,         // clock divide
  0xA8, 0x3F,         // 64 rows
  0xD3, 0x00,         // no offset
  0x40,               // start at row 0
  0x8D, 0x14,         // charge pump on
  0x20, 0x00,         // horizontal addressing: columns, then pages
  0xA1, 0xC8,         // mirror so (0, 0) is the top left
  0xDA, 0x12,         // COM pins for 128x64
  0x81, 0xCF,         // contrast
  0xD9, 0xF1,         // pre-charge
  0xDB, 0x40,         // VCOMH level
  0xA4, 0xA6,         // show RAM, not inverted
  0xAF,               // display on
};
static const uint8_t WINDOW[] = { 0x00, 0x21, 0, 127, 0x22, 0, 7 };   // every column and page

// 5x7 glyphs, one byte per column, lowest bit on top: the digits, then the letters the text uses.
static const char LETTERS[] = "0123456789STMUptimes:";
static const uint8_t FONT[][5] = {
  {0x3E, 0x51, 0x49, 0x45, 0x3E}, {0x00, 0x42, 0x7F, 0x40, 0x00}, {0x42, 0x61, 0x51, 0x49, 0x46},
  {0x21, 0x41, 0x45, 0x4B, 0x31}, {0x18, 0x14, 0x12, 0x7F, 0x10}, {0x27, 0x45, 0x45, 0x45, 0x39},
  {0x3C, 0x4A, 0x49, 0x49, 0x30}, {0x01, 0x71, 0x09, 0x05, 0x03}, {0x36, 0x49, 0x49, 0x49, 0x36},
  {0x06, 0x49, 0x49, 0x29, 0x1E}, {0x46, 0x49, 0x49, 0x49, 0x31}, {0x01, 0x01, 0x7F, 0x01, 0x01},
  {0x7F, 0x02, 0x0C, 0x02, 0x7F}, {0x3F, 0x40, 0x40, 0x40, 0x3F}, {0x7C, 0x14, 0x14, 0x14, 0x08},
  {0x04, 0x3F, 0x44, 0x40, 0x20}, {0x00, 0x44, 0x7D, 0x40, 0x00}, {0x7C, 0x04, 0x18, 0x04, 0x78}, {0x38, 0x54, 0x54, 0x54, 0x18},
  {0x48, 0x54, 0x54, 0x54, 0x20}, {0x00, 0x36, 0x36, 0x00, 0x00},
};

static void text(int x, int page, const char *s) {
  for (; *s; s++, x += 6) {
    const char *at = strchr(LETTERS, *s);
    if (*s == ' ' || !at) continue;
    for (int c = 0; c < 5; c++) pixels[page * 128 + x + c] = FONT[at - LETTERS][c];
  }
}

static void dot(int x, int y) {
  if (x >= 0 && x < 128 && y >= 0 && y < 64) pixels[(y / 8) * 128 + x] |= 1u << (y % 8);
}

int main(void) {
  RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOBEN;
  RCC->APB1ENR |= RCC_APB1ENR_USART2EN | RCC_APB1ENR_I2C1EN;
  GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER2) | GPIO_MODER_MODER2_1;
  GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(0xFu << 8)) | (7u << 8);   // PA2: AF7, USART2 TX
  USART2->BRR = SystemCoreClock / 115200;                       // 16 MHz HSI after reset
  USART2->CR1 = USART_CR1_TE | USART_CR1_UE;

  // PB8 and PB9: alternate function 4 (I2C1), open-drain.
  GPIOB->MODER = (GPIOB->MODER & ~(GPIO_MODER_MODER8 | GPIO_MODER_MODER9)) | GPIO_MODER_MODER8_1 | GPIO_MODER_MODER9_1;
  GPIOB->OTYPER |= GPIO_OTYPER_OT8 | GPIO_OTYPER_OT9;
  GPIOB->AFR[1] = (GPIOB->AFR[1] & ~0xFFu) | (4u << 0) | (4u << 4);
  I2C1->CR2 = 16;      // APB1 at 16 MHz
  I2C1->CCR = 80;      // 16 MHz / (2 x 80) = 100 kHz
  I2C1->TRISE = 17;    // 1000 ns rise time: 16 MHz clock + 1
  I2C1->CR1 = I2C_CR1_PE;

  SysTick->LOAD = SystemCoreClock / 1000 - 1;   // 1 ms
  SysTick->VAL = 0;
  SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk;

  i2c_write(OLED, SETUP, sizeof SETUP);
  printf("OLED ready\r\n");
  frame[0] = 0x40;   // control byte: pixel data follows

  int x = 20, y = 40, dx = 3, dy = 2;
  char uptime[24];
  while (1) {
    memset(pixels, 0, 128 * 8);
    text(0, 0, "STM32");
    snprintf(uptime, sizeof uptime, "Uptime: %lu s", (unsigned long)(ticks / 1000));
    text(0, 2, uptime);
    for (int i = 0; i < 128; i++) { dot(i, 26); dot(i, 63); }
    for (int j = 26; j < 64; j++) { dot(0, j); dot(127, j); }
    x += dx;
    y += dy;
    if (x < 5 || x > 122) dx = -dx;
    if (y < 31 || y > 58) dy = -dy;
    for (int i = -4; i <= 4; i++)
      for (int j = -4; j <= 4; j++)
        if (i * i + j * j <= 16) dot(x + i, y + j);

    i2c_write(OLED, WINDOW, sizeof WINDOW);
    i2c_write(OLED, frame, sizeof frame);
  }
}

Lessons behind it