Trash or Nah

For this week’s project, I used an Ultrasonic distance sensor as my analog input to create a box that opens its lid when you are far away from it. Once you come close enough with your hands over the box, it will shut on you. The goal of the project is to tempt the user to come close, but once you come too close, it will surprise and close on you. Ideally, the cover would be much heavier so that if it shuts, the person’s hand would be trapped there.

The Ultrasonic distance sensor is faced upwards so that it can detect whether there is a hand over it or not. Depending on its distance value, I map it to the servo, which will rotate between 50 to 180 degrees. I have attached a cardboard on the servo wing so that it is heavier and strong enough to hold up the cardboard box on top. In its neutral 50 degree, the cardboard does not push on the lid, however, once a hand gets close enough, the servo will rotate and will bring the cardboard with it to raise the lid. I have also included a Piezo buzzer that beeps more and more often once a hand gets close to it and a red LED light will also turn on.

During the project, I had problem figuring out what degrees to set the servo so that it went exactly between the 90 degrees needed to lift the lid. Additionally, the distance sensor takes a while to get the correct value, so there are times when every 10ms, it would jump between 1 and 403. To stop that from happening, I added a bit of a delay, but I’m not sure if that’s the correct way to fix it.

To improve on this project, I would probably also mount the servo in a more stable way rather than just hot gluing it to the side because it kept tilting to one side.

 

Attached is the code for the program :

#include <Servo.h>;

Servo servo;
int lightPin = 8;
int buzzerPin = 9;
int servoPin = 10;
int trigPin = 11;
int echoPin = 12;

void setup() {
  Serial.begin(9600);
  servo.attach(servoPin);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(lightPin, OUTPUT);
}

void loop() {
  int distanceInches = getCurrentDistance();
  int pos = 50;
  if (distanceInches <= 30) {
    pos = map(distanceInches, 1, 30, 150, 180);
    tone(buzzerPin, 3000, map(pos, 150, 180, 30, 200));
    delay(10);
  }

  if (pos != 50) {
    analogWrite(lightPin, map(pos, 150, 180, 50, 255));
  } else {
    digitalWrite(lightPin, LOW);
  }
  
  Serial.println(distanceInches);
  servo.write(pos);
}

float getCurrentDistance() {
  float dist;
  float echoT;

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  echoT = pulseIn(echoPin, HIGH);
  dist = echoT / 148.0; //microseconds to inches

  return dist;
}

Leave a Reply