Why does this not work? 😩

There is an ultrasonic sensor conrolling a servo, it won't work even with this code from (https://Instuctables). I tried my own code I tried switching parts, I tried changing wires.
What makes it worse is it used to work and i need it done in a couple days. Is it broken because I put in a box with a battery pack?

#include <Servo.h> 

#define trigPin 9

#define echoPin 8

Servo servo;

int sound = 250;

void setup() {
  
  Serial.begin(9600);

  pinMode(trigPin, OUTPUT);

  pinMode(echoPin, INPUT);

  servo.attach(6);

}

void loop() {

  long duration, distance;

  digitalWrite(trigPin, LOW);

  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10);

  digitalWrite(trigPin, LOW);

  duration=pulseIn(echoPin, HIGH);

  distance=(duration/2)/29.1;if(distance<80){

    Serial.print(distance);

    Serial.println(" cm");

    servo.write(90);

  }

  else if(distance<180); {

    Serial.print(distance);

    Serial.println(" cm");

    servo.write(180);}


  delay(500);

}





What type of battery are you using ?

Is it a 9V PP3 by any chance ?

I am using 4 1.5 volt triple a batteries.

So you have a 6V supply

How is it connected to the Uno ?

Through GND pin and Vin pin

The Vin voltage should be at least 7V

OK
but my UNO also does not work with USB

You appear to be powering your servo from the Uno's 5V pin.

What is the stall current of your servo?

How much current can your USB port supply?

And in the event you power the Uno through the barrel connector with sufficient voltage (>7V), can the Uno's 5V regulator supply the servo's stall current? (Hint: likely not).

If it used to work when powered by USB and now doesn't then what has changed ?

The answer is not "nothing has changed"

Check all of the connections to make sure that they go to the right pins and that there is continuity from one end of each lead to the other

The Arduino 5V output cannot be used for motors and servos. Use 4xAA batteries instead (see below).

Also, the servo library interferes with some uses of pin 9, so try using other pins for the ultrasonic sensor.

#define trigPin 9
#define echoPin 8

I am powering my servo through 3.3v pin

The USB aparently gives 5 volts

That is even worse. Servos require 4.8 to 6 V at high currents.

What should i do though its the same with Vin

Really? Interesting. What is the minimum supply voltage for your servo?

And how much current can the Uno's 3.3V regulator supply?

4.8 ~ 6 V DC Volts

Which question was that the answer to ?

It was the answer to van_der_deckens question
"Interesting. What is the minimu supply voltage for your servo?"

If the servo's operating range is 4.8 to 6V, then 3.3V volts is unlikely to do the job. Also, you did not answer how much current the Uno's 3.3V regulator can supply. Another hint: it's not enough to power a servo, even if the voltage was within range.

does Vin work?

I just tried Vin it does not work

:frowning_face: