I'm trying to code an ultrasonic distance sensor to activate 2 servo motors when the distance measured is less than 50 cm. So far I can get the readings right but the motors don't move. Does this code look ok to you? Is something wrong with it?
I can make everything work separately... Make the motors move without the sensor... The problem is that once I try to put everything together, they stop moving
This is my first time trying to do something with Arduino on my own, so I apologize in advance if the problem is super easy to solve and I just couldn't figure it out x)
I'm trying to code an ultrasonic distance sensor to activate 2 servo motors when the distance measured is less than 50 cm. So far I can get the readings right but the motors don't move. Does this code look ok to you? Is something wrong with it?
#include <NewPing.h>
#include <Servo.h>
#define TRIGGER_PIN 11 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 12 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
Servo myservo2; // create servo2 object to control a servo
int pos = 0; // variable to store the servo position
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
Serial.begin(115200);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
myservo2.attach(10); // attaches the servo2 on pin 10 to the servo object
}
void loop() {
delay(1000);
Serial.print("Ping: ");
Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside setdistance range)
Serial.println("cm");
if (sonar.ping_cm() < 50 && sonar.ping_cm() > 1) { // if distance is less then 50 cm and greater 1 cm
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
myservo2.write(pos); // tell servo2 to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
myservo2.write(pos); // tell servo2 to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
} else { //do nothing
pos = 0; {
myservo.write(pos);
myservo2.write(pos);
delay(15); // waits 15ms for the servo to reach the position
}
}
}