For an assignment we must make two servos sweep while a photocell attached to one senses a light source and stops the loop when it's pointed at a light. Right now i'm just trying to get the base code we were given to work right. For some reason only one of the servos will move (sero 2, connected to pin 11). I'm trying to figure out why the other servo won't move. I do not have the code for stopping the loop with the sensor yet.
// Light Detector (2 D)
//
// This program continuously sweeps a servo back and forth while making
// readings from a connected photocell.
//
#include <Servo.h>
const int SENSOR = 3;
int val = 0;
Servo myservo1; // create servo object to control a servo
Servo myservo2; // create servo object to control a servo
int pos1 = 0; // variable to store the servo1 position
int pos2 = 0; // variable to store the servo2 position
void setup() {
myservo1.attach(10);
myservo2.attach(11);
Serial.begin(9600);
}
void loop() {
for(pos1 = 0; pos1 < 180; pos1 += 1) {
myservo1.write(pos1); //position servo
for(pos2 = 0; pos2 < 180; pos2 += 1) {
myservo2.write(pos2); //position servo
delay(10);
val = analogRead(SENSOR); //read current sensor value
Serial.println(val); //print it via serial port
} // for pos2
for(pos2 = 180; pos2 >=0; pos2 -= 1) {
myservo2.write(pos2); //position servo
delay(10);
val = analogRead(SENSOR); //read current sensor value
Serial.println(val); //print it via serial port
} // for pos2
} // for pos1
for(pos1 = 180; pos1 >=0; pos1 -= 1) {
myservo1.write(pos1); //position servo
for(pos2 = 0; pos2 < 180; pos2 += 1) {
myservo2.write(pos2); //position servo
delay(10);
val = analogRead(SENSOR); //read current sensor value
Serial.println(val); //print it via serial port
} // for pos2
for(pos2 = 180; pos2 >=0; pos2 -= 1) {
myservo2.write(pos2); //position servo
delay(10);
val = analogRead(SENSOR); //read current sensor value
Serial.println(val); //print it via serial port
} // for pos2
} // for pos1
}
I suspect both servos are moving but servo1 very slowly. Because you have nested the for loops servo1 moves 1 degree, then servo2 moves the full 180 and then back then servo1 moves another 1 degree etc. Was that really what you meant it to do?
The goal is to have the LDR move around by the servos and stop when its pointing at a light source strong enough to trigger it. My professor's instructions were a bit unclear, but by the way his provided base code works, the base servo moves a bit, waits for the top servo (with the LDR) to do a full sweep (0-180-0) and then increment another small degree. In which case I think the nested for loops are required.
Slipstick was right and the base servo was only moving 1 degree after every sweep and I just didn't see that, and after increasing the increment amount, I could see the movements working properly. I then added a while loop to stop the loop when the LDR sensor value was high enough, per the assignment's instructions.