from machine import Pin, I2C, ADC
import ssd1306
import time
print("=== LAB 10 DEMO (WOKWI FIXED) ===")
# ================= OLED =================
i2c = I2C(1, sda=Pin(6), scl=Pin(7), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# ================= SIMULATED ACCELEROMETER =================
adc_x = ADC(26)
adc_y = ADC(27)
# ================= BUTTON =================
button = Pin(3, Pin.IN, Pin.PULL_UP)
running = True
btn_flag = False
last_press = 0
def button_irq(pin):
global btn_flag, last_press
now = time.ticks_ms()
if time.ticks_diff(now, last_press) > 300:
btn_flag = True
last_press = now
button.irq(trigger=Pin.IRQ_FALLING, handler=button_irq)
# ================= SIMPLE CIRCLE FUNCTION =================
def draw_circle(x0, y0, r):
for x in range(-r, r):
for y in range(-r, r):
if x*x + y*y <= r*r:
oled.pixel(x0 + x, y0 + y, 1)
# ================= MAIN LOOP =================
while True:
if btn_flag:
btn_flag = False
running = not running
if not running:
oled.fill(0)
oled.text("PROGRAM OFF", 20, 28)
oled.show()
time.sleep(0.3)
continue
raw_x = adc_x.read_u16()
raw_y = adc_y.read_u16()
acc_x = (raw_x / 65535) * 2 - 1
acc_y = (raw_y / 65535) * 2 - 1
center_x = 64
center_y = 32
scale = 25
circle_x = int(center_x + acc_x * scale)
circle_y = int(center_y - acc_y * scale)
if circle_x < 6: circle_x = 6
if circle_x > 122: circle_x = 122
if circle_y < 6: circle_y = 6
if circle_y > 58: circle_y = 58
oled.fill(0)
oled.text("ACC_X={:+.2f}".format(acc_x), 0, 0)
oled.text("ACC_Y={:+.2f}".format(acc_y), 0, 10)
draw_circle(circle_x, circle_y, 5)
oled.show()
print("ACC_X={:+.2f} ACC_Y={:+.2f}".format(acc_x, acc_y))
time.sleep(0.1)