I’m working on a project which has falling objects non stop into a tray. The goal of my project is to detect when the tray is full and ready to be emptied. When it is full an alarm will sound which indicates the operator. I decided to use a sonar sensor to detect that, however I am running into an issue. When the objects are passing by the sensor they are tripping it and turning on the alarm too quickly. I want it to only detect when the pile reaches the desired height of the sensor. My thoughts were to use a delay or millis to test the inchdistance <= 6 twice. However, when I implement either of those methods the sonar sensor stops reading and on the second condition test it just reads the previous value. Any help or suggestions would be greatly appreciated.
#define trigPin 6 // Connect trigpin to D6 on Arduino
#define echoPin 5 // Connect echopin to D5 on Arduino
#define ledPin A3
#define btnPin 7
// defines variables
long duration; // It's a variable for the duration of sound wave travel
int inchdistance; // It's a variable for measurement of distance in inches
int cmdistance; // It's a variable for measurement of distance in centimeters
int btnState = 0; // Reading status of button
int var = 0;
int varTray = 0;
int trayFull = 0;
int interval;
unsigned long currentMillis = 0;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
pinMode(ledPin, OUTPUT);
pinMode(btnPin, INPUT_PULLUP);
pinMode(13, OUTPUT);
Serial.begin(9600); // // For Serial Communication
}
void loop() {
digitalWrite(trigPin, LOW); // Clears the trigPin condition
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
// Calculating the distance
inchdistance = duration * 0.0133858 / 2; // To calculate the distance in inch
cmdistance = duration * 0.034 / 2; // To calculate the distance in cm
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(inchdistance);
Serial.println(" inch");
Serial.print(cmdistance);
Serial.println(" cm");
btnState = digitalRead(btnPin);
// if(inchdistance <= 6){
// currentMillis = millis();
// interval = currentMillis + 2000;
// while(currentMillis < interval){
// currentMillis = millis();
// }
// varTray = 1;
// }
if(inchdistance <= 6){
delay(5000);
if(inchdistance <= 6){
trayFull = 1;
}
}
if(trayFull == 1 & var == 0){
var = 1;
digitalWrite(ledPin, HIGH);
}
else if(btnState == LOW & var == 1){
digitalWrite(ledPin, LOW);
var = 0;
trayFull = 0;
varTray = 0;
delay(5000);
}
digitalWrite(13, digitalRead(btnPin));
}