from machine import Pin, I2C
import ssd1306
# ESP32 Pin assignment
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
wpx = 8
hpx = 8
gap = 10
padding = 5
texts = ['MicroPython', 'for', 'ESP32 S3']
def max_length():
max = texts[0]
for text in texts:
if len(text) > len(max):
max = text
return max
def total_size():
width = wpx * len(max_length())
height = hpx * len(texts) + (len(texts) - 1) * gap
return width, height
def text_pixels():
dict = {}
for text in texts:
x = len(text) * wpx
y = hpx
dict[text] = [x, y]
return dict
def coordinates():
x_coordinates = []
y_coordinates = []
width, height = total_size()
for i in range(len(texts)):
pixels = text_pixels().get(texts[i])
x = (oled_width - pixels[0])//2
x_coordinates.append(x)
if not y_coordinates:
y = (oled_height - height)//2
y_coordinates.append(y)
else:
y = y_coordinates[i-1] + gap + hpx
y_coordinates.append(y)
return x_coordinates, y_coordinates
def display_text():
x_cor, y_cor = coordinates()
oled.fill(0)
for i in range(len(texts)):
x = x_cor[i]
y = y_cor[i]
oled.text(texts[i], x, y, 1)
oled.show()
def display_frame():
x_cor, y_cor = coordinates()
width, height = total_size()
x1 = x_cor[0] - padding
y1 = y_cor[0] - padding
w = width + padding * 2
h = height + padding
oled.rect(x1, y1, w, h, 1)
oled.show()
display_text()
display_frame()