ssd1306的micropython驱动代码
时间: 2023-05-29 09:01:26 浏览: 489
以下是一个基本的SSD1306驱动程序的MicroPython代码:
```python
from machine import Pin, I2C
import framebuf
# I2C初始化
i2c = I2C(-1, Pin(5), Pin(4))
# SSD1306常量定义
WIDTH = 128
HEIGHT = 64
class SSD1306(object):
def __init__(self, width, height):
self.width = width
self.height = height
# 创建缓冲区
self.buffer = bytearray((self.width//8) * self.height)
# 创建帧缓冲区对象
self.framebuf = framebuf.FrameBuffer(self.buffer, self.width, self.height, framebuf.MVLSB)
# 初始化SSD1306
self.init_display()
def init_display(self):
# 基本配置
self.write_command(0xAE) # 关闭OLED显示
self.write_command(0xD5) # 设置高速时钟分频率
self.write_command(0x80) # 时钟分频率设置,值越小时钟速度越快
self.write_command(0xA8) # 设置多路复用率
self.write_command(self.height-1)
self.write_command(0xD3) # 设置显示显示位置移动模式
self.write_command(0x00) # 不移动(默认)
self.write_command(0x40|0x00) # 设置显示首列的位置
self.write_command(0xA0|0x01) # 列地址从左到右
self.write_command(0xC8) # 行地址从上到下
self.write_command(0xDA) # 设置COM硬件引脚配置
self.write_command(0x12)
self.write_command(0x81) # 对比度设置
self.write_command(0x7F)
self.write_command(0xA4) # 关闭全局显示模式
self.write_command(0xA6) # 设置正常显示模式
self.write_command(0xAF) # 打开OLED显示
def poweroff(self):
self.write_command(0xAE)
def poweron(self):
self.write_command(0xAF)
def contrast(self, contrast):
self.write_command(0x81)
self.write_command(contrast)
def invert(self, invert):
if invert:
self.write_command(0xA7) # 反色显示
else:
self.write_command(0xA6) # 正常显示
def show(self):
# 设置内存窗口位置
self.write_command(0x21)
self.write_command(0)
self.write_command(self.width-1)
self.write_command(0x22)
self.write_command(0)
self.write_command(self.height-1)
# 写入帧缓冲区
i2c.writeto(0x3c, self.buffer)
def fill(self, fill_val):
self.framebuf.fill(fill_val)
def pixel(self, x, y, color):
self.framebuf.pixel(x, y, color)
def scroll(self, dx, dy):
self.framebuf.scroll(dx, dy)
def hline(self, x, y, w, color):
self.framebuf.hline(x, y, w, color)
def vline(self, x, y, h, color):
self.framebuf.vline(x, y, h, color)
def rect(self, x, y, w, h, color):
self.framebuf.rect(x, y, w, h, color)
def fill_rect(self, x, y, w, h, color):
self.framebuf.fill_rect(x, y, w, h, color)
def blit(self, fbuf, x, y):
self.framebuf.blit(fbuf, x, y)
def write_command(self, command):
i2c.writeto(0x3c, bytes([0x00, command]))
def write_data(self, data):
i2c.writeto(0x3c, bytes([0x40, data]))
# 创建SSD1306对象及初始化
oled = SSD1306(WIDTH, HEIGHT)
```
上述代码中实例化了一个SSD1306类的对象用于控制显示,该类中包含了一些方法用于控制显示内容及属性。该代码已经在ESP8266上完成测试,应该可以在其他MicroPython开发板上运行。
阅读全文