import machine
import utime
from machine import Pin, PWM, ADC # Fixed: Added ADC and removed trailing comma
### \==========================================
### 1\. HARDWARE SETTINGS
### \==========================================
PAIN\_THRESHOLD = 65000
### \==========================================
### 2\. HARDWARE CONFIGURATION & INITIALIZATION
### \==========================================
### Servo Gate (PWM)
servo = PWM(Pin(9))
servo.freq(50)
### Ultrasonic Sensor
trig = Pin(5, Pin.OUT)
echo = Pin(6, Pin.IN)
### Sound Sensor (Analog)
sound\_sensor = ADC(Pin(26))
### Playtime Switch
time\_switch = Pin(7, Pin.IN, Pin.PULL\_UP)
### \==========================================
### 3\. HELPER DRIVER FUNCTIONS
### \==========================================
def set\_gate\_angle(angle):
duty = int(1638 + (angle / 180) \* (8192 - 1638))
servo.duty\_u16(duty)
def get\_distance():
trig.low()
utime.sleep\_us(2)
trig.high()
utime.sleep\_us(10)
trig.low()
signaloff = utime.ticks\_us()
signalon = utime.ticks\_us()
timeout = utime.ticks\_us()
while echo.value() == 0:
signaloff = utime.ticks\_us()
if utime.ticks\_diff(signaloff, timeout) > 30000:
return -1
timeout = utime.ticks\_us()
while echo.value() == 1:
signalon = utime.ticks\_us()
if utime.ticks\_diff(signalon, timeout) > 30000:
return -1
return ((signalon - signaloff) \* 0.0343) / 2
### \==========================================
### 4\. MAIN OPERATIONAL LOOP
### \==========================================
while True:
sound\_level = sound\_sensor.read\_u16()
is\_playtime = time\_switch.value() == 0
distance = get\_distance()
\# === EMERGENCY OVERRIDE: Pain Sound Triggers Whole Array ===
if sound\_level > PAIN\_THRESHOLD:
set\_gate\_angle(0) # Slam the gate shut
print("!! ALARM !!") # Fixed: Fixed Python indentation
print("Pain Sound Heard")
print("Level: " + str(sound\_level))
else: # Fixed: Added missing 'else' to separate alarm from regular logic
if is\_playtime:
print("PLAYTIME!") # Fixed: Removed display coordinates from normal print statements
if 0 < distance < 10:
set\_gate\_angle(90)
print("Hamster at door")
print("Gate: OPEN")
else:
set\_gate\_angle(0)
print("No hamster seen")
print("Gate: CLOSED")
else:
set\_gate\_angle(0)
print("BEDTIME")
print("System: LOCKED")
print("Gate: CLOSED")
utime.sleep\_ms(200)