Drive OLED with official SSD1306.py

I looked at micropython's I2C OLED driver (similar to SPI) these days and found that there are several versions. One is the official version, and there are early versions circulating on the Internet.

The online version uses pyb.I2C driver, which is transplanted from Arduino's OLED driver, and can only be used on STM32; while the official driver uses machine.I2C, which has better compatibility and is suitable for different hardware platforms. Software I2C can also be used.

Because no one has introduced the official SSD1306 driver, I will briefly introduce the OLED usage of the I2C interface, and the SPI is similar. The following is an example of the more common 0.96-inch 128x64 I2C OLED:

  • Download the source code of micropython from github (or just download the ssd1306.py file in it), then copy the ssd1306.py to the PYB Nano or other micropython board
  • Connect the I2C and power to the I2C OLED, if there is no hardware I2C, you can use any GPIO.
  • Enter the following code in the terminal
from machine import I2C
i2c=machine.I2C(-1, sda=machine.Pin("PB9"), scl=machine.Pin("PB8"), freq=400000)  

from ssd1306 import SSD1306_I2C
oled = SSD1306_I2C(128, 64, i2c)
oled.text("Hello PYB Nano", 0, 0)
oled.show()


If you can see the text Hello, it means that the driver is successful.

 

There are not many functions in SSD1306.py. The main functions are:

  • text(string, x, y), display the string at (x, y), note that the built-in font of the text() function is 8x8, which cannot be replaced temporarily
  • poweroff(), turn off the OLED display
  • poweron(), an empty function, has no effect. Can be replaced with write_cmd(0xAF)
  • fill(n), n=0, clear the screen, n is greater than 0, fill the screen
  • contrast(), adjust the brightness. 0 is the darkest, 255 is the brightest
  • invert(), invert display for odd numbers, normal display for even numbers
  • pixel(x, y, c), draw a point at (x, y)
  • show(), update the display content. Most of the previous functions just write data to the buffer, and will not display it directly to the screen. You need to call show() to display it.


In addition, some functions can be implemented in the following ways:

  • framebuf.line(x1,y1,x2,y2,c), draw a straight line
  • framebuf.hline(x,y,w,c), draw a horizontal line
  • framebuf.vline(x,y,w,c), draw a vertical line
  • framebuf.fill_rect(x,y,w,h,c), draw a filled rectangle
  • framebuf.rect(x,y,w,h,c), draw a hollow rectangle

You can also encapsulate it yourself, and even add functions such as painting garden, font selection, and logo display.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324524306&siteId=291194637
Recommended