#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <Stepper.h>
#define BLYNK_TEMPLATE_ID "TMPLcTOERftz"
#define BLYNK_TEMPLATE_NAME "Roller blind"
#define BLYNK_AUTH_TOKEN "WCyUrdTruziX1sJyh5DuYQtpx5vWA7Qp"
#define LDR_PIN 2
#define LED_PIN 4
#define AUTOMATIC V1
#define OPEN V2
#define CLOSE V3
#define LAMP V4
bool isAutomaticMode = true;
bool isClosing;
bool isOpening;
bool isLampTurnedOn = true;
char auth[] = BLYNK_AUTH_TOKEN;
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
const int stepsPerRevolution = 200;
const int MAX_STEPS = 1200;
const int MIN_STEPS = 0;
Stepper rollerStepper(stepsPerRevolution, 26, 27, 14, 12);
int currentStep = MIN_STEPS;
// This function is called every time the device is connected to the Blynk.Cloud
// Request the latest state from the server
BLYNK_CONNECTED() {
Blynk.syncVirtual(AUTOMATIC);
Blynk.syncVirtual(OPEN);
Blynk.syncVirtual(CLOSE);
Blynk.syncVirtual(LAMP);
}
// This function is called every time the Virtual Pin state change
//i.e when web push switch from Blynk App or Web Dashboard
BLYNK_WRITE(AUTOMATIC) {
isAutomaticMode = param.asInt();
if (isAutomaticMode) {
//update switchers states
Blynk.virtualWrite(AUTOMATIC, 1);
Blynk.virtualWrite(OPEN, 0);
Blynk.virtualWrite(CLOSE, 0);
isClosing = false;
isOpening = false;
}
}
BLYNK_WRITE(OPEN) {
isOpening = param.asInt();
if (isOpening) {
//update switchers states
Blynk.virtualWrite(AUTOMATIC, 0);
Blynk.virtualWrite(OPEN, 1);
Blynk.virtualWrite(CLOSE, 0);
isClosing = false;
isAutomaticMode = false;
}
}
BLYNK_WRITE(CLOSE) {
isClosing = param.asInt();
if (isClosing) {
//update switchers states
Blynk.virtualWrite(AUTOMATIC, 0);
Blynk.virtualWrite(OPEN, 0);
Blynk.virtualWrite(CLOSE, 1);
isOpening = false;
isAutomaticMode = false;
}
}
BLYNK_WRITE(LAMP) {
isLampTurnedOn = param.asInt();
digitalWrite(LED_PIN, isLampTurnedOn);
}
void setup() {
pinMode(LDR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
rollerStepper.setSpeed(60);
Blynk.begin(auth, ssid, pass);
}
void loop() {
Blynk.run();
if (isAutomaticMode) {
if (digitalRead(LDR_PIN) == HIGH && currentStep < MAX_STEPS) {
// dark
rollerStepper.step(1);
currentStep++;
} else if (digitalRead(LDR_PIN) == LOW && currentStep > MIN_STEPS) {
// bright
rollerStepper.step(-1);
currentStep--;
}
} else if (isOpening) {
if (currentStep > MIN_STEPS) {
rollerStepper.step(-1);
currentStep--;
} else if (currentStep <= MIN_STEPS) {
Blynk.virtualWrite(OPEN, 0);
}
} else if (isClosing) {
if (currentStep < MAX_STEPS) {
rollerStepper.step(1);
currentStep++;
} else if (currentStep >= MAX_STEPS) {
Blynk.virtualWrite(CLOSE, 0);
}
}
delay(10);
}