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)
# Joystick Pins
joystick_x_pin = Pin(4, Pin.IN)
joystick_y_pin = Pin(2, Pin.IN)
def draw_character(data, x, y):
for row in range(16): # 遍歷每一行,因為我們的字型是16x16的點陣圖
for byte_index in range(2): # 因為我們是以8位的byte來存儲,一行需要2個byte(16位元)
# 根據行數和位元組索引來計算我們在資料中的位置
byte_val = data[row * 2 + byte_index]
# 計算X軸的起始位置。我們知道每個位元組有8個點,所以乘以8
x_0 = x + byte_index * 8
# 計算Y軸的位置,因為我們在遍歷每一行時,y座標會增加
y_0 = y + row
for bit in range(8): # 遍歷位元組中的每一位
# 這裡我們使用一個遮罩來檢查byte_val中的特定位元是否為1。
# 1 << (7 - bit) 會產生如下的遮罩: 10000000, 01000000, ... , 00000001
# 然後我們用位元與運算(&)來檢查byte_val的這一位是否被設為1。
if byte_val & (1 << (7 - bit)):
oled.pixel(x_0 + bit, y_0, 1) # 如果是1,則在OLED上繪製一個點
print('1', end='') # 也在終端上印出1
else:
print(' ', end='') # 如果不是,則在終端上印出空格
print() # 在終端上換行,以對應到下一行的繪製
character_data = [
0x00, 0x00,
0x00, 0x00,
0x7f, 0xfe,
0x7f, 0xfe,
0x63, 0xc6,
0x6b, 0xd6,
0x63, 0xc6,
0x7f, 0xfe,
0x7f, 0xfe,
0x03, 0xc0,
0x0f, 0xf0,
0x0f, 0xf0,
0x03, 0xc0,
0x7f, 0xfe,
0x7f, 0xfe,
0x00, 0x00
]
# Initial position of the character
character_x = 56
character_y = 24
# Main loop
while True:
oled.fill(0) # Clear the display
# Read joystick inputs
joystick_x = joystick_x_pin.value()
joystick_y = joystick_y_pin.value()
# Adjust joystick inputs to consider center as (0, 0)
joystick_x_adjusted = (joystick_x - 0.5) * 2
joystick_y_adjusted = (joystick_y - 0.5) * 2
# Update character position based on adjusted joystick inputs
character_x += joystick_x_adjusted
character_y += joystick_y_adjusted
# Ensure the character stays within the OLED bounds
character_x = max(0, min(oled_width - 16, int(character_x)))
character_y = max(0, min(oled_height - 16, int(character_y)))
# Draw the character at the updated position
draw_character(character_data, character_x, character_y)
# Refresh the OLED to see the character
oled.show()