Preview:
// Define ultrasonic sensor pin connections
#define TRIGGER_PIN 2
#define ECHO_PIN 3

// Define LED pin connections for waste bins
#define GREEN_LED_PIN 6
#define RED_LED_PIN 7
#define BLUE_LED_PIN 8

unsigned long previousMillis = 0;
unsigned long currentMillis = 0;
unsigned long elapsedTime = 0;

void setup() {
  Serial.begin(9600);
  
  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  
  pinMode(GREEN_LED_PIN, OUTPUT);
  pinMode(RED_LED_PIN, OUTPUT);
  pinMode(BLUE_LED_PIN, OUTPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);
  
  duration = pulseIn(ECHO_PIN, HIGH);
  distance = (duration / 2) / 29.1; // Calculate distance in centimeters
  
  currentMillis = millis();
  elapsedTime = currentMillis - previousMillis;

  if (elapsedTime >= 0 && elapsedTime < 15000) { // 0-30 seconds
    delay(2000); // 2 seconds delay
  } else if (elapsedTime >= 15000 && elapsedTime < 30000) { // 30-60 seconds
    delay(1000); // 1 second delay
  } else if (elapsedTime >= 30000 && elapsedTime < 45000) { // 30-60 seconds
    delay(500); // 1 second delay
  } else if (elapsedTime >= 45000 && elapsedTime < 60000) { // 30-60 seconds
    delay(250); // 1 second delay
  } else if (elapsedTime >= 60000) { // 60 seconds and after
    delay(100); // 0.5 second delay
  }

  if (distance < 10) {
    activategreen(); // If object is close, activate green bin LED
    Serial.println("RECYCLABLE");
  } else if (distance >= 10 && distance < 20) {
    activatered(); // If object is at medium distance, activate red bin LED
    Serial.println("NON_RECYCLABLE");
  } else if (distance >= 20 && distance < 30) {
    activateblue(); // If object is at far distance, activate blue bin LED
    Serial.println("COMPOSTABLE");
  }
  
  delay(100); // Adjust delay as needed for data transmission
}

void activategreen() {
  digitalWrite(GREEN_LED_PIN, HIGH); // Turn on green LED
  digitalWrite(RED_LED_PIN, LOW); // Turn off red LED
  digitalWrite(BLUE_LED_PIN, LOW); // Turn off blue LED
}

void activatered() {
  digitalWrite(GREEN_LED_PIN, LOW); // Turn off green LED
  digitalWrite(RED_LED_PIN, HIGH); // Turn on red LED
  digitalWrite(BLUE_LED_PIN, LOW); // Turn off blue LED
}

void activateblue() {
  digitalWrite(GREEN_LED_PIN, LOW); // Turn off green LED
  digitalWrite(RED_LED_PIN, LOW); // Turn off red LED
  digitalWrite(BLUE_LED_PIN, HIGH); // Turn on blue LED
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter