Can someone explain to me why my code isnt working?

My project is a trash bin that opens and closes by a servo when the ultrasonic sensor detects something. All my parts are new, and it is wired correctly so im confused on why it is not working. If you want anything else like schematics or anything just ask in replys.

//defining trig and echo pin
#define trigPin 2
#define echoPin 3

//defining servo pin
#define servoPin 5

//library implimintation
#include <Servo.h>

//defining servo name
Servo servo1;

//a variable to store the servo position
int angle = 0;

// define the maximum distance that the ultrasonic sensor can detect
const int MAX_DISTANCE = 50;

//defining the variables
long duration;
int distance;

void setup() 
{
  //defining inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  


  //the servo is now attatched to pin 9 or the servo pin
  servo1.attach(servoPin);

  //Begining the serial communication at a rate of 9600
  Serial.begin(9600);

}

void loop() {
  //Clearing the trigPin by setting it to LOW
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);

  //Triggering the sensor by setting the trigPin to high for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);

  // Calculate the distance:
  distance = duration * 0.034 / 2;

  // Print the distance on the Serial Monitor (Ctrl+Shift+M):
  Serial.print("Distance = ");
  Serial.print(distance);
  Serial.println(" cm");

//only activate the servo if the distance has changed
  static int prevDistance = 0;
  if (distance != prevDistance) {
    prevDistance = distance;
    //if the distance is less then than the max distance, activate servo/open lid
    if (distance < MAX_DISTANCE) {
      servo1.write(80); //open lid to 80 degrees
      delayMicroseconds(1000); //leave open for 0.1 seconds
    }

    else {
      servo1.write(0); //close lid
      delayMicroseconds(1000); //leave closed for 0.1 seconds
    }
      

  }


} // Made by me

This is my code and for some reason it wont work, i have no clue why, the only thing that does work is that I get a response from my ultrasonic sensor but the servo wont work.

1000us is 1ms (.001sec) not 0.1 seconds

Thanks, but this did not fix my issue

Post an annotated schematic as you have it wired, a frizzy wiring diagram does not have enough data to solve problems. Be sure to show all power sources, grounds etc. Links showing technical information on each of the hardware devices will help a lot. Note links to azon or similar marketplace sellers normally do not have the needed information.

Did you test the electronics and servo before you nailed it to the waste bin?

What’s your power supply?

Maybe add some Serial.prints to see what your code is doing.

Hi,
How do you mean it is not working?

What does the IDE monitor display as an object approaches the sensor?

Can we please have a circuit diagram?
An image of a hand drawn schematic will be fine, include ALL power supplies, component names and pin labels.
Can you please post some images of your project so we can see your component layout?

Do you have a DMM.

Can I suggest you use NewPing Library to do ALL your ultrasonic calculations?

Thanks.. Tom.. :smiley: :+1: :coffee: :australia:

basically the servo motor wont move when it detects something within the required range.

Here is schematic. Sorry for the bad annotation aswell as here is the link for the servo motor

Here is servo link and schematic link

I suggest that you slow the code down. Leave about 50ms between pings so that the echo from one ping can die down before the next.

//defining trig and echo pin
#define trigPin 2
#define echoPin 3

//defining servo pin
#define servoPin 5

//library implimintation
#include <Servo.h>

//defining servo name
Servo servo1;

//a variable to store the servo position
int angle = 0;

// define the maximum distance that the ultrasonic sensor can detect
const int MAX_DISTANCE = 50;

//defining the variables
long duration;
int distance;

void setup()
{
   //defining inputs and outputs
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);



   //the servo is now attatched to pin 9 or the servo pin
   servo1.attach(servoPin);

   //Begining the serial communication at a rate of 9600
   Serial.begin(9600);

}

void loop()
{
   static unsigned long timer = 0;
   unsigned long interval = 50;
   if (millis() - timer >= interval)
   {
      timer = millis();
      //Clearing the trigPin by setting it to LOW
      digitalWrite(trigPin, LOW);
      delayMicroseconds(5);

      //Triggering the sensor by setting the trigPin to high for 10 microseconds
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
      duration = pulseIn(echoPin, HIGH);

      // Calculate the distance:
      distance = duration * 0.034 / 2;

      // Print the distance on the Serial Monitor (Ctrl+Shift+M):
      Serial.print("Distance = ");
      Serial.print(distance);
      Serial.println(" cm");

      //only activate the servo if the distance has changed
      static int prevDistance = 0;
      if (distance != prevDistance)
      {
         prevDistance = distance;
         //if the distance is less then than the max distance, activate servo/open lid
         if (distance < MAX_DISTANCE)
         {
            Serial.println(" open");
            servo1.write(80); //open lid to 80 degrees
            delayMicroseconds(1000); //leave open for 0.1 seconds
         }

         else
         {
            Serial.println(" close");
            servo1.write(0); //close lid
            delayMicroseconds(1000); //leave closed for 0.1 seconds
         }
      }
   }
} // Made by me

This code seems to work (I am not sure what you expect) on my Uno with and HC05 and micro servo. Servo moves when range becomes less than 50 and moves back when range increases over 50.

Your servo should not be powered by the Arduino. Arduino is not a power supply. if the servo jitters, it is likely lacking power.

What is the target for the rangefinder. A good target is solid, flat and perpendicular to the sensor. Fluffy kitties or cloth curtains, for instance, are not good targets.

The code shows the servo connected to pin 5.

That is not an annotated schematic, it is a fuzzy frizzy which many of us do not read. It is missing power sources ground connections etc. It does not agree with your code. Good luck, I will check later in a few days looking for the schemat. Doing this will also answer questions posed by others.

If you are seeing “Open” and “Closed” but the servo isn’t moving, try powering it from a separate more suitable power supply that can output 6 volts. Be sure to connect the grounds otherwise it still won’t work.

The target would be something like my hand or leg, something i can just wave infront of it. Im still decently new to arduino stuff, so how would i go about powering the servo by something else?

Three common options.

  1. Battery packs (probably won’t last very long)
  2. Recycle a wallwort power supply that can output 6v at 1000ma or better
  3. Get a 7-9V power supply to power both the servo and arduino with the help of voltage regulators. You may want something better than 1000ma.

A 4 AA cell battery pack is a good battery supply. What ever the external supply, connect the grounds.

Connect like so:
image

A bare hand or leg is not a bad target. Loose clothing would be a bad target as it will absorb the ping.

```and the fuzzy fritzy shows Pin9 connected  
:smirk: