print("Baby guardian")
print("By:Afifi")
print("Date:29/4/2024\n\n")
# import library
from machine import Pin, SoftI2C, PWM
from utime import sleep
import ultrasonic_lib
import oled_lib
import servo_lib
# pin declaration
led_hijau = Pin(18, Pin.OUT)
led_merah = Pin(5, Pin.OUT)
oled = SoftI2C(scl=Pin(22), sda=Pin(21))
Trig = Pin(12)
Echo = Pin(13)
servo_pin = Pin(14, Pin.OUT)
buzzer_pin = 2 # Adjust the pin according to your setup
buzzer_pwm = PWM(Pin(buzzer_pin))
# parameter declaration
# create object name for sensor with library--->object_name=library_name.class_name()
skrin = oled_lib.SSD1306_I2C(width=128, height=64, i2c=oled)
sonic = ultrasonic_lib.HCSR04(trigger_pin=12, echo_pin=13, echo_timeout_us=500 * 2 * 30)
gate = servo_lib.Servo(pin=servo_pin)
def play_tone(frequency, duration):
"""
Play a tone of a given frequency and duration.
"""
buzzer_pwm.freq(frequency)
buzzer_pwm.duty(100) # Adjust duty cycle as needed (between 0 to 1023)
sleep(duration)
buzzer_pwm.duty(0)
# Define note frequencies for "Twinkle, Twinkle, Little Star"
NOTE_C4 = 261
NOTE_G4 = 392
NOTE_A4 = 440
NOTE_F4 = 349
NOTE_E4 = 330
NOTE_D4 = 294
def play_twinkle_twinkle():
"""
Play the melody of "Twinkle, Twinkle, Little Star".
"""
melody = [
NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4,
NOTE_G4, NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_D4,
NOTE_D4, NOTE_C4
]
durations = [
0.5, 0.5, 0.5, 0.5, 0.5, 0.5,
1, 0.5, 0.5, 0.5, 0.5, 0.5,
1, 2
]
# Play the melody
for note, duration in zip(melody, durations):
play_tone(note, duration)
sleep(0.2)
# main program
while True:
jarak_cm = sonic.distance_cm()
jarak_mm = sonic.distance_mm()
buzzer_pwm.init(freq=1500, duty=0)
if jarak_cm <= 50:
gate.move(angle=0)
led_merah.on()
sleep(0.2)
led_merah.off()
sleep(0.2)
skrin.fill(0)
skrin.text("Baby dah dekat", 5, 20, 1)
skrin.text(str(jarak_cm), 5, 30, 1)
skrin.text("CM", 70, 30, 1)
skrin.show()
led_hijau.off()
# Play Twinkle Twinkle melody
play_twinkle_twinkle()
elif 50 <= jarak_cm <= 200:
buzzer_pwm.init(freq=1500, duty=100)
sleep(0.2)
buzzer_pwm.init(freq=1500, duty=0)
sleep(3)
gate.move(angle=90)
led_hijau.on()
sleep(0.2)
led_hijau.off()
sleep(0.2)
sleep(0.05)
skrin.fill(0)
skrin.text("Baby jauh lagi", 5, 20, 1)
skrin.text(str(jarak_cm), 5, 30, 1)
skrin.text("CM", 70, 30, 1)
skrin.show()
else:
led_hijau.on()
gate.move(angle=90)
skrin.fill(0)
skrin.text("Selamat", 5, 20, 1)
skrin.text(str(jarak_cm), 5, 30, 1)
skrin.text("CM", 70, 30, 1)
skrin.show()
led_merah.off()
sleep(0.2)