import RPi.GPIO as GPIO
import time
# 핀 설정
TRIG = 17
ECHO = 27
BUZZER = 22
BUTTON = 5
# GPIO 모드 설정
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
GPIO.setup(BUZZER, GPIO.OUT)
GPIO.setup(BUTTON, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# PWM 설정
buzzer = GPIO.PWM(BUZZER, 1)
buzzer.start(0)
# 초기 상태 설정
state = "IDLE"
F1 = 0
F2 = 0
# Input.txt 파일로부터 주파수 읽기
with open('input.txt', 'r') as file:
frequencies = file.read().split()
F1 = int(frequencies[0])
F2 = int(frequencies[1])
def change_state(channel):
global state
if state == "IDLE":
state = "LAZY"
elif state == "LAZY":
state = "NORMAL"
else:
state = "IDLE"
def measure_distance():
GPIO.output(TRIG, False)
time.sleep(2)
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance, 2)
return distance
# 버튼 이벤트 설정
GPIO.add_event_detect(BUTTON, GPIO.FALLING, callback=change_state, bouncetime=300)
try:
while True:
distance = measure_distance()
if state == "IDLE":
buzzer.ChangeDutyCycle(0)
elif state == "LAZY":
if distance <= 100:
buzzer.ChangeFrequency(F1)
buzzer.ChangeDutyCycle(50)
else:
buzzer.ChangeDutyCycle(0)
elif state == "NORMAL":
if distance <= 100:
buzzer.ChangeFrequency(F1)
buzzer.ChangeDutyCycle(50)
elif distance <= 200:
buzzer.ChangeFrequency(F2)
buzzer.ChangeDutyCycle(50)
else:
buzzer.ChangeDutyCycle(0)
time.sleep(1)
except KeyboardInterrupt:
print("Measurement stopped by User")
GPIO.cleanup()