import machine
import time
import BlynkLib
import network
import utime
# Define pins for stepper motor and PIR sensor
DIR_PIN = 14
STEP_PIN = 15
PIR_PIN = 18
# Initialize the pins
dir_pin = machine.Pin(DIR_PIN, machine.Pin.OUT)
step_pin = machine.Pin(STEP_PIN, machine.Pin.OUT)
pir_sensor = machine.Pin(PIR_PIN, machine.Pin.IN)
# Blynk setup
BLYNK_AUTH = '91VBEXDTK3DkpEvUa6CZ7PBVePFuJ_yY' # Replace with your Blynk Auth Token
wifi_ssid = 'Wokwi-GUEST' # Replace with your Wi-Fi SSID
wifi_password = '' # Replace with your Wi-Fi password
# Connect to Wi-Fi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(wifi_ssid, wifi_password)
print('Connecting to network...')
while not wlan.isconnected():
print('Waiting for connection...')
utime.sleep(1)
print('Connected to Wi-Fi')
blynk = BlynkLib.Blynk(BLYNK_AUTH)
# Variables to store Blynk control states
sensor_enabled = False
# Blynk virtual pin handlers
def blynk_connected():
print(" Connected to Blynk")
@blynk.on("connected")
def blynk_connected_handler():
blynk_connected()
@blynk.on("V0")
def v0_write_handler(value):
global sensor_enabled
sensor_enabled = value[0]
print('Sensor enabled:', sensor_enabled)
# Function to control the stepper motor
def swing_motor(duration_minutes):
end_time = time.time() + (duration_minutes * 60)
while time.time() < end_time:
dir_pin.value(1)
for _ in range(100):
step_pin.value(1)
time.sleep(0.01) # Adjust this for slower motion
step_pin.value(0)
time.sleep(0.01)
time.sleep(0.1) # Pause at the end of each swing
dir_pin.value(0)
for _ in range(100):
step_pin.value(1)
time.sleep(0.01)
step_pin.value(0)
time.sleep(0.01)
time.sleep(0.1) # Pause at the end of each swing
# Main loop
while True:
blynk.run()
if sensor_enabled and pir_sensor.value() == 1:
print('Motion detected')
blynk.log_event("motion_detected")
swing_motor(5)
time.sleep(1) # Delay to avoid multiple notifications