Hello
Im a new one, so I don
t know how to write the code correctly
I need to control two servo motors with two ultrasonic sensors on arduino uno
1.Servo 1 needs to rotate to 90 degrees only when Ultrasonic1 gets the data that is <=7cm, if it is more goes back to satrt position
2.Servo 1 needs to rotate to 90 degrees and Servo 2 needs to rotate to 83 degrees when Ultrasonic 2 gets data that is <=7, if it is more goes back to satrt position
3.If both of Ultrasonics get data that is <=7 than run programm 2
The most difficult thing is that everything should be in one code!
If somebody could help me with that, I would be grateful!
Hello!
First, you need to use the Ultrasonic library to read the values from the ultrasonic sensors.
After that, you need to use the Servo library to move your servo according to your criteria.
So, the code is very simple:
#include <Ultrasonic.h>
#include <Servo.h>
// Pins used by your servos. Adjust according to your connections.
#define pin_servo1 3
#define pin_servo2 4
// Pins used by your ultrasonic sensors. Adjust according to your connections.
#define pin_trigger1 5
#define pin_trigger2 6
#define pin_echo1 7
#define pin_echo2 8
float v1_dist_cm, v1_dist_in, v2_dist_cm, v2_dist_in;
Servo srv1;
Servo srv2;
Ultrasonic ultra1(pin_trigger1, pin_echo1);
Ultrasonic ultra2(pin_trigger2, pin_echo2);
void setup()
{
srv1.attach(pin_servo1);
srv2.attach(pin_servo2);
srv1.write(0);
srv2.write(0);
}
void loop()
{
// Read ultrasonic values
long microsec1 = ultra1.timing();
long microsec2 = ultra2.timing();
// Distance in inches and in centimeters
v1_dist_cm = ultra1.convert(microsec1, Ultrasonic::CM);
v1_dist_in = ultra1.convert(microsec1, Ultrasonic::IN);
v2_dist_cm = ultra2.convert(microsec2, Ultrasonic::CM);
v2_dist_in = ultra2.convert(microsec2, Ultrasonic::IN);
// According to your readings, you move the servos:
if (v1_dist_cm <= 7 && v2_dist_cm > 7) {
srv1.write(20);
}
else
{
srv1.write(0);
}
if (v1_dist_cm > 7 && v2_dist_cm <= 7) {
srv1.write(20);
srv2.write(40);
}
else
{
srv1.write(0);
srv2.write(0);
}
if (v1_dist_cm <= 7 && v2_dist_cm <= 7) {
// Put your "program 2" here.
}
}
The values for servos are arbitrary, you need to put the values that make sense to you, in the 0 - 180 range.
I think this solves your problem. Adjust/improve as needed. Good luck.
Update: the Ultrasonic library can be downloaded here: