from machine import Pin, PWM, ADC, I2C, time_pulse_us
import time
from i2c_lcd import I2cLcd
from lcd_api import LcdApi
# === Pin Setup ===
trig = Pin(20, Pin.OUT)
echo = Pin(21, Pin.IN)
pir = Pin(18, Pin.IN)
potensio = ADC(26)
servo = PWM(Pin(3))
servo.freq(50)
buzzer = PWM(Pin(12))
led = Pin(9, Pin.OUT)
button = Pin(5, Pin.IN, Pin.PULL_UP)
# === LCD Setup ===
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16) # 2 baris x 16 karakter
lcd.clear()
lcd.putstr("Sistem Palang")
# === Global State ===
mode_potensio = False
servo_active = False
last_press = 0
# === Tombol Interrupt ===
def toggle_mode(pin):
global mode_potensio, last_press
now = time.ticks_ms()
if time.ticks_diff(now, last_press) > 300:
mode_potensio = not mode_potensio
print(">> MODE:", "Potensio" if mode_potensio else "Ultrasonik")
lcd.clear()
lcd.putstr("Mode:\n")
lcd.putstr("Potensio" if mode_potensio else "Ultrasonik")
last_press = now
button.irq(trigger=Pin.IRQ_FALLING, handler=toggle_mode)
# === Servo Function ===
def set_servo(deg):
min_duty = 1638
max_duty = 8192
duty = int(min_duty + (max_duty - min_duty) * deg / 180)
servo.duty_u16(duty)
# === Distance Measurement ===
def get_distance():
trig.low()
time.sleep_us(2)
trig.high()
time.sleep_us(10)
trig.low()
try:
pulse = time_pulse_us(echo, 1, 30000)
distance = pulse * 0.0343 / 2
except:
distance = 999
time.sleep(0.05)
return distance
# === LED & Buzzer ===
def aktifkan_efek(aktif):
if not aktif:
led.value(0)
buzzer.duty_u16(0)
return
if pir.value():
# Ada gerakan = pelanggaran
led.toggle()
buzzer.freq(600)
buzzer.duty_u16(30000)
lcd.clear()
lcd.putstr("Pelanggaran!")
time.sleep(0.1)
led.toggle()
buzzer.duty_u16(0)
time.sleep(0.1)
else:
# Normal berkedip lambat
led.toggle()
time.sleep(0.4)
led.toggle()
time.sleep(0.4)
# === Loop Utama ===
while True:
if mode_potensio:
val = potensio.read_u16()
sudut = int(val / 65535 * 90)
print("Potensio:", sudut)
set_servo(sudut)
servo_active = sudut >= 85
else:
jarak = get_distance()
print("Jarak:", jarak)
if jarak < 50:
set_servo(90)
servo_active = True
else:
set_servo(0)
servo_active = False
if servo_active:
lcd.clear()
lcd.putstr("Palang: Tutup")
else:
lcd.clear()
lcd.putstr("Palang: Buka")
aktifkan_efek(servo_active)