Hi, i want to make servo motor work when ultrasonic read reach > 40 cm
#include <NewPing.h>
#include <Servo.h>
Servo myservo;
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 13 // 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.
#define US_VCC 11
#define servo_vcc 2
#define servo_gnd 1
int pos = 0;
int val;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
pinMode(US_VCC,OUTPUT);
myservo.attach(3);
pinMode(servo_gnd,OUTPUT);
pinMode(servo_vcc,OUTPUT);
}
void loop() {
digitalWrite(US_VCC,HIGH);
digitalWrite(servo_vcc,HIGH);
digitalWrite(servo_gnd,LOW);
delay(50);
// Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
Serial.print("Ping: ");
Serial.print(sonar.ping_cm()); // Send ping, get distance in cm and print result (0 = outside set distance range)
Serial.println("cm");
val=sonar.ping_cm();
if (val > 40 )
servo_on();
}
void servo_on(){
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'
delay(15); // waits 15 ms 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'
delay(15); // waits 15 ms for the servo to reach the position
}
}
i noticed that when i remove servo lines the ultrasonic work fine, and when i remove ultrasonic lines the servo work fine, where is the problem ??
Hi,
which arduino are you using?
Are you using port 1 for the motor?
In some arduino models, (perhaps even all), this port is part of the serial and it is not recommended to use it for other activities.
Why do you not power the servo from power pins - 5v and GND?
The maximum output current of arduino digital pin is 40mA, recommended - 20mA. The most of servos need far much current.
The using the digital pin as GND is non-sense at all.
You are risking damage to the pins connected to servo power and ground connections. They can't safely handle the current.
I see you are powering the ultrasonic the same way. No good.
By the way, a Fritzing diagram isn't a schematic either, it's a parts layout diagram. In this case it's simple enough that you can get away with it. A more complex circuit, no way.
i know i will face power problem in future, the project i want to work on is a GPS guided robot. the components i want to use are a GPS, GSM, Compass module, 4 DC motors for 4 wheels, and 2 servo motors.
Do you have suggestions?
im still new to arduino and never heard about this, do you have something to read about it