from machine import Pin, I2C
import time
import ssd1306
# ---------------- OLED SETUP ----------------
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Fix OLED orientation
oled.rotate_180()
# ---------------- PIR SENSOR ----------------
pir = Pin(13, Pin.IN)
# ---------------- STEPPER (A4988) ----------------
step = Pin(26, Pin.OUT)
dir = Pin(27, Pin.OUT)
direction = 1
steps_per_rev = 200
# ---------------- FUNCTIONS ----------------
def display(status):
oled.fill(0)
oled.text("Motion System", 0, 0)
oled.text(status, 0, 20)
oled.text("Dir: " + ("CW" if direction else "CCW"), 0, 40)
oled.show()
def rotate_motor():
global direction
display("Moving...")
for i in range(steps_per_rev):
step.value(1)
time.sleep_us(1000) # slower = stable in Wokwi
step.value(0)
time.sleep_us(1000)
# reverse direction
direction = not direction
dir.value(direction)
# ---------------- INITIAL ----------------
dir.value(direction)
display("Idle")
# ---------------- MAIN LOOP ----------------
while True:
if pir.value() == 1:
display("Motion Detected")
rotate_motor()
time.sleep(2) # prevent retrigger
else:
time.sleep(0.2)