This is an automatic trash bin. One HCSR-04 Ultrasonic sensor controls a SG90 servomotor that opens the lid while the other sensor indicates when the bin is full with a LED. It works fine at times and at others it powers the motor directly without there being any presence in front of the sensor over and over again. Is it the code?
This is the code I am using:
#include <Servo.h>
Servo servo;
int trigPin = 5;
int echoPin = 6;
int trigPin2 = 8;
int echoPin2 = 9;
int servoPin = 10;
int LED1= 7;
long duration, dist, average;
long aver[3];
void setup() {
Serial.begin(9600);
servo.attach(servoPin);
pinMode(LED1,OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
servo.write(0);
delay(100);
servo.detach();
}
void loop() {
int bduration, bdistance;
digitalWrite(trigPin2, LOW);
delayMicroseconds(4);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
bduration = pulseIn(echoPin2, HIGH);
bdistance = (bduration/2) / 29.1;
int duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(4);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 10)
{
servo.attach(servoPin);
delay(1);
servo.write(120);
delay(7000);
servo.write(0);
delay(1000);
servo.detach();
}
if (bdistance < 16)
{
digitalWrite(LED1, HIGH);
}
else
{
digitalWrite(LED1, LOW);
}
delay(50);
}