Section 3.5 OLED display
Micropython has built-in support for displaying simple graphics, and there are already libraries to interface with a number of displays. In this section, we'll be using a common OLED display model, the SSD1306.
Subsection 3.5.1 S2 Pico built-in OLED
The Wemos S2 Pico has a built-in OLED display, as well as drivers ready to go. We can use it with the following code:
from s2pico_oled import OLED
from machine import Pin, I2C
i2c = I2C(0, sda=Pin(8), scl=Pin(9)) # Pins 8 and 9 are hard-wired
oled = OLED(i2c, Pin(18)) # Pin 18 is hard-wired to reset the display
oled.test() # Remove this test once you start displaying your own stuff
The MicroPython documentation 1 describes the various functions you can call to control the display:
display.poweroff() # power off the display, pixels persist in memory
display.poweron() # power on the display, pixels redrawn
display.contrast(0) # dim
display.contrast(255) # bright
display.invert(1) # display inverted
display.invert(0) # display normal
display.rotate(True) # rotate 180 degrees
display.rotate(False) # rotate 0 degrees
display.show() # send your drawing to the display
And there are a set of functions you can use to draw stuff:
display.fill(0) # fill entire screen with color=0
display.pixel(0, 10) # get pixel at x=0, y=10
display.pixel(0, 10, 1) # set pixel at x=0, y=10 to color=1
display.hline(0, 8, 4, 1) # horizontal line x=0, y=8, width=4, color=1
display.vline(0, 8, 4, 1) # vertical line x=0, y=8, height=4, color=1
display.line(0, 0, 127, 63, 1) # line from 0,0 to 127,63
display.rect(10, 10, 107, 43, 1) # rectangle outline 10,10 to 117,53, color=1
display.fill_rect(10, 10, 107, 43, 1) # solid rectangle 10,10 to 117,53, color=1
display.text('Hello World', 0, 0, 1) # some text at x=0, y=0, color=1
Note that calling these drawing functions sets the values of pixels, but doesn't actually send them to the display. To see the changes, you'll need to call display.show()
.
Subsection 3.5.2 Wiring an external display
Below is a complete code example for an SSD1306 OLED display that you've wired up manually. You'll need to make sure you have the ssd1306.py library copied to the ESP32.
# This assumes that you've connected it as follows:
# GND -> GND
# VCC -> 3.3V
# SCL -> D2
# SDA -> D4
from machine import Pin, I2C
import ssd1306
from time import sleep
# Set up the display
i2c = I2C(0, scl=Pin(2), sda=Pin(4))
display = ssd1306.SSD1306_I2C(128, 64, i2c)
# Now show some text on the display
display.fill(0) # First clear the display with 0 (black)
display.text("Hello!", 5, 5) # Draw text located at pixel (5, 5)
display.show() # Send the pixel data to the display to show it
docs.micropython.org/en/latest/esp8266/tutorial/ssd1306.html