基于Adafruit_SSD1306的ssd1306OLED局部刷新

基于Adafruit_SSD1306的ssd1306OLED局部刷新

刚好最近在做树莓派项目的时候用到了Adafruit_SSD1306模块来控制ssd1306主控的显示屏,发现模块并没有提供局部刷新的方法。看了源码后发现在display方法中用到了列指针和页指针,于是修改了一下,给添加了局部刷新的方法。 连接方式如图,图片源于网络,侵删!

import Adafruit_SSD1306
from Adafruit_SSD1306 import SSD1306_COLUMNADDR
from Adafruit_SSD1306 import SSD1306_PAGEADDR
from Adafruit_SSD1306 import SSD1306_128_64
from Adafruit_SSD1306 import SSD1306_128_32


class Mixin:

    def image_local(self, image):
    """
    仅去除了源代码中对大小的限制,添加了新的图片容器
    """
        if image.mode != 1:
            raise ValueError(Image must be in mode 1.)
        imwidth, imheight = image.size
        
        if imwidth != self.width or imheight != self.height:
            raise ValueError(Image must be same dimensions as display ({0}x{1}). 
                .format(self.width, self.height))
        
        # Grab all the pixels from the image, faster than getpixel.
        pix = image.load()
        # Iterate through the memory pages
        index = 0
        page = imheight // 8
        self._buffer_local = [0] * (imwidth * page)
        for page in range(page):
            # Iterate through all x axis columns.
            for x in range(imwidth):
                # Set the bits for the column of pixels at the current position.
                bits = 0
                # print(page, x)
                # Dont use range here as its a bit slow
                for bit in [0, 1, 2, 3, 4, 5, 6, 7]:
                    bits = bits << 1
                    bits |= 0 if pix[(x, page * 8 + 7 - bit)] == 0 else 1
                # Update buffer byte and increment to next byte.
                self._buffer_local[index] = bits
                index += 1

    def display_local(self, position=None):
        position(x,y,width,height)
            大小必须与image一致
            由于page是以8个像素点为单位的,图片的高以及纵坐标最好为8的倍数
        
        if not position:
            position = (0, 0, self.width, self.height)
        """Write display buffer to physical display."""
        self.command(SSD1306_COLUMNADDR)
        self.command(position[0])  # Column start address. (0 = reset)
        self.command(position[0] + position[2] - 1)  # Column end address.
        self.command(SSD1306_PAGEADDR)
        self.command(position[1] // 8)  # Page start address. (0 = reset)
        self.command((position[1] + position[3]) // 8 - 1)  # Page end address.
        # Write buffer data.
        if self._spi is not None:
            # Set DC high for data.
            self._gpio.set_high(self._dc)
            # Write buffer.
            self._spi.write(self._buffer_local)
        else:
            for i in range(0, len(self._buffer_local), 16):
                control = 0x40  # Co = 0, DC = 0
                self._i2c.writeList(control, self._buffer_local[i:i + 16])

class SSD1306_128_64_S(Mixin, SSD1306_128_64): pass
class SSD1306_128_32_S(Mixin, SSD1306_128_32): pass
经验分享 程序员 微信小程序 职场和发展