Currently i use an Arduino Uno, HC-SR04 sensor and a MG995 Servo motor, while trying to supply these components with my 9V battery nothing works with me but i can see that the Arduino UNO board is on because of its lights, i already bought a cable for the 9V so do i need another battery such as a 12V if not please lead me to another solution.
Never use 9V smoke alarm type batteries for projects.
You're not powering your servo +5V with Arduino, are you? That also goes against Arduino best practices.
Your battery selection depends on a number of things.
Please provide full project details, such as a hand drawn schematic. Also the project housing, whether it's portable or fixed, and ideally, the code, using code tags.
// defines variables
long duration;
int distance;
void setup()
{
servo.attach(6);
servo.write(0);
delay(2000);
// Sets the trigPin as an Output
pinMode(trigPin, OUTPUT);
// Sets the echoPin as an Input
pinMode(echoPin, INPUT);
// Starts the serial communication
Serial.begin(9600);
}
void loop()
{
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(100);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.0343/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
if ( distance <= 25 ) // Change Distance according to Ultrasonic Sensor Placement
{
servo.write(0);
}
else
{
servo.write(180);
}
delay(3000);
}
This is the code im using and yes i am powering my servo with 5V
Just a tip with that code, you're driving it to either extreme end with 0 and 180 degrees in your servo.write() calls. I like to limit mine to 10 and 170 degrees maximum if I drive them with servo.write() to help prolong the life of the servo.
The sensor can connect to the Arduino 5V output.
Using a 9V battery connected to Vin or the barrel jack to power the Arduino and a separate 4AA battery pack to power the servo is the simplest solution.
You could also use 6AA batteries and a buck converter.
If your servo wires are Red, Black and Yellow
Connect the positive lead of the AA pack to Red
Connect the negative lead of the AA pack to Black
Connect the servo Yellow wire to a digital pin
IMPORTANT:
Also connect the servo Black wire to the Arduino GND