Hey, so I basically just started doing this project (Also clarify that I'm not putting together this yet, I'ts being done in Tinkercad right now).
I decided to do an automatic windows with a few functions (In a smaller scale), the functions are that when someone from outside the house is too close, the windows close automatically, this function works with an ultrasound sensor, and the other one is that when it's raining the windows also closes automatically, this one is done with the "soil moisture sensor".
This is supposed to be done by the servos rotating 90 degrees, but for some reason when one or both of the conditions are true the servos just start twitching, I have been trying to figure out why this happens, but no idea, I don't know if this is a problem with the simulation since I'm a beginner so if anyone could help me it would be great. (I'm attaching the code and an image of the simulation)
Here is the code:
#include <Servo.h>
const int sensorH = A0;
const int trigPin = 7;
const int echoPin = 6;
int WindowState = 0;
int servoR = 10;
int servoL = 11;
int humidity = 0;
int distanceA = 0;
int humidityA = 0;
Servo right;
Servo left;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
right.attach(servoR);
left.attach(servoL);
}
void loop() {
humidity = analogRead(sensorH);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
float distance = duration * 0.034 / 2;
if (distance < 50 && WindowState == 0) {
distanceA = 1;
}
else if(distance > 50 || WindowState == 1) {
distanceA = 0;
}
if (humidity > 500 && WindowState == 0) {
humidityA = 1;
}
else if (humidity < 500 || WindowState == 1 ){
humidityA = 0;
}
if (distanceA == 1 || humidityA == 1){
WindowState = 1;
}
else if (distanceA == 0 && humidityA == 0){
WindowState = 0;
}
if (WindowState == 1){
right.write(90);
left.write(90);
}
else if (WindowState == 0){
right.write(0);
left.write(0);
}
delay(100);
}