You know how I was wondering about how to display images on the OLED display using MicroPython? No? Hmm. Well, anyway, I was. And I figured it out. Not thanks to all the online articles.
Actually I did find a GitHub repository that included a conversion script that turns .png files into binary files that the OLED can display.
Except that in the examples provided the author, and others elsewhere, talk about creating a buffer and blitting that to the display created with the SSD1306 MicroPython library, and neither of my copies of that library have a blit() method. Okay, it’s in the framebuf class so, well anyway my code was still throwing up errors complaining about not having a blit() method.
That left me to guess how the binary files were ordered and how to get that data onto the screen.
I used the conversion script to make an example bitmap and saved a copy to the Pico. First I did a bit of setup. I needed cols because the display is chunked horizontally into 8 pixel blocks, with each pixel receiving a value of 1 or 0 from the bits in the data byte
bWidth = 128
bHeight = 64
cols = bWidth // 8
Then I figured out how to read the binary file with:
filename = "spotx"
with open(filename, 'rb') as file:
data = file.read()
Then, by trial and error, I created the following abomination:
index = 0
for i in range(bHeight):
for col in range(cols):
aByte = data[index]
for bitCounter in range(8):
bit = (aByte & 128) // 128
display.pixel(col * 8 + bitCounter, i ,bit)
aByte = aByte << 1
index += 1
display.show()
It iterates down the display from the top left, proceeding in 8 pixel horizontal chunks. It grabs a byte (which is actually an int) from the loaded file and loops through the bits in the byte, masking out all except the MSB. Then it does an integer divide by 128 to get a result of 0 or 1 to indicate whether the pixel should be on or off.
Once it’s got the pixel value it sends it to the display at the appropriate coordinate. It repeats the process for the rest of the current byte before fetching a new one.
Finally, it updates the display and the bitmap appears just like magic but actually by the power of science!!!
You can be sure I didn’t know what the [redacted] I was doing and the first few iterations resulted in a jumble of pixels but who cares about that? What’s important is that I can display a picture again.
Hooray.