from picozero import Speaker
from machine import Pin, ADC, PWM
from time import sleep
from machine import Pin
from utime import sleep
import time
Servo_Pin = 26
Speaker_Pin = 15
Pot_Pin = 28
GreenPin = 4
YellowPin = 3
RedPin = 2
GreenPin2 = 12
YellowPin2 = 13
RedPin2 = 14
SwitchPin = 8
RedLED = Pin(RedPin, Pin.OUT)
YellowLED = Pin(YellowPin, Pin.OUT)
GreenLED = Pin(GreenPin, Pin.OUT)
RedLED2 = Pin(RedPin2, Pin.OUT)
YellowLED2 = Pin(YellowPin2, Pin.OUT)
GreenLED2 = Pin(GreenPin2, Pin.OUT)
Switch = Pin(SwitchPin, Pin.IN, Pin.PULL_DOWN)
# Potentiometer (Analog)
potentiometer = ADC(Pin(Pot_Pin))
# Servo
servo_pwm = PWM(Pin(Servo_Pin))
servo_pwm.freq(50)
#speaker
Buzzer = Speaker(Speaker_Pin)
speaker_pwm = PWM(Pin(Speaker_Pin))
MIN_DUTY = 1638 # 0 degrees
MAX_DUTY = 8192 # 180 degrees
DUTY_RANGE = MAX_DUTY - MIN_DUTY
def play_tone(frequency, duration):
"""Plays a tone on the speaker."""
if frequency > 0:
speaker_pwm.freq(int(frequency))
# A duty cycle of 512 out of 1024 (or ~50% of the max duty) is typical
# For full 16-bit resolution (0-65535), 50% is 32768
speaker_pwm.duty_u16(32768)
time.sleep(duration)
speaker_pwm.duty_u16(0) # Stop the sound
else:
speaker_pwm.duty_u16(0)
def set_servo_angle(angle):
"""Calculates and sets the PWM duty cycle for the servo."""
# Clamp the angle between 0 and 180 degrees
angle = max(0, min(180, angle))
# Map the angle to the duty cycle range (MIN_DUTY to MAX_DUTY)
duty = int((angle / 180) * DUTY_RANGE + MIN_DUTY)
servo_pwm.duty_u16(duty)
last_angle = -1
TONE_DURATION = 0.05
print("Starting Potentiometer-Servo-Speaker Control")
# when all the lights are off
def all_lights_off():
RedLED.value(0)
YellowLED.value(0)
GreenLED.value(0)
RedLED2.value(0)
YellowLED2.value(0)
GreenLED2.value(0)
def normal_traffic_lights():
RedLED.value(1)
RedLED2.value(1)
time.sleep(1)
# 1.
RedLED.value(0)
GreenLED.value(1)
# RedLED2 remains ON
time.sleep(5)
# 2.
GreenLED.value(0)
YellowLED.value(1)
time.sleep(2)
# 3.
YellowLED.value(0)
RedLED.value(1)
time.sleep(1)
# 4.
RedLED2.value(0)
GreenLED2.value(1)
time.sleep(5)
# 5.
GreenLED2.value(0)
YellowLED2.value(1)
time.sleep(2)
# 6.
YellowLED2.value(0)
RedLED2.value(1)
time.sleep(1)
# emergency state
def emergency_state():
all_lights_off()
# turn the red lights on
RedLED.value(1)
RedLED2.value(1)
time.sleep(0.2)
# Turn both LED's OFF
RedLED.value(0)
RedLED2.value(0)
time.sleep(0.5)
while True:
pot_value = potentiometer.read_u16()
switch_state = Switch.value()
current_angle = int(pot_value * 180 / 65535)
set_servo_angle(current_angle)
if abs(current_angle - last_angle) > 1:
if current_angle > last_angle:
play_tone(880, TONE_DURATION)
else:
play_tone(440, TONE_DURATION)
last_angle = current_angle
if switch_state == 1:
print("EMERGENCY STATE ACTIVE")
emergency_state()
else:
print("NORMAL TRAFFIC MODE ACTIVE")
speaker_pwm.duty_u16(0)
normal_traffic_lights()
time.sleep(0.05)