I am currently using a breadboard with 2 servos connected and an arduino with the servos connected too. I also have a hc-sro4 connected to the arduino and need help coding. Whenever i run the servos sometimes they don't work. and even if they do work, they run backwards after executing my commands to them
Hi,
We need more info! how are the servos connected how are you powering them, not from the arduino I hope! it can't supply the current they need, a seperate 6v is needed.
Let us see your schematic (or a good clear photo) and code, THEN we can help.
Regards
Mel.
Thanks for responding.
My 2 servos are have GND and Power connected to the breadboard, but have the signal wires connected to ports 9 & 10 on the arduino. The HC-SR04 sensor has GND and Power on the arduino and also has Trig and Echo connected to ports 4 & 2 respectively.
Regards, HOWDOESITNOTWORK.
Code:
#include <Servo.h>
#define trigPin 4
#define echoPin 2
Servo servo1;
Servo servo2;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
servo1.attach(9);
servo2.attach(10);
int pos1 = 0;
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(2);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
if (distance < 10) {
for (int pos1 = 0; pos1 < 180; pos1 += 1) {
servo2.write(pos1);
delay(15);
}
}
}
Always power servos from a separate power supply, capable of 1 ampere per servo. Connect the grounds.
Hi,
Your code looks OK, but why the Serial.begin? So where is the problem, again how are you powering the servos?
Here's the code I use on one of my bots:
------------------------------------------------------------------
long scanner(long cm)
{
const int pingPin=2, EchoPin=3;
long duration;
// The SRF005 is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse before to ensure a clean HIGH pulse:
pinMode(pingPin, OUTPUT);
pinMode(EchoPin, INPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(2);
digitalWrite(pingPin, LOW);
duration = pulseIn(EchoPin, HIGH);
delay(100);
// convert the time into a distance
// inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
return (cm);
}
//------------------------------------------------------------------
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimetre.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
Hope it helps, regards
Mel.