Need help with solar tracker

I am trying to make a circuit that will always turn to pint towards the brightest light to maximise solar power with an arduino uno, a servo and a turntable. All the circuitry is good and my code is telling the motor to turn towards the light, but it won't stop when it gets there. it will just turn around and around and never stop. I'm new at this so I'm not sure what to do. Help please.

/*
 * code to make a solar panel point towards the sun(or brightest light) with a servo motor
 */
#include <Servo.h> // include servo library

Servo myservo; // declare motor
int pos = 0; // servo motor position
int inputLeft = A0; // light sensor on the left (attached to analog pin 0)
int inputRight = A1; // light sensor on the right (attached to analog pin 1)
int left = 0; // value of left sensor
int right = 0; // value of right sensor

void setup() {
  pinMode(inputLeft, INPUT); // tell the circuit board that the sensors are inputs
  pinMode(inputRight, INPUT); // tell the circuit board that the sensors are inputs
  myservo.attach(9); // tell the circuit board that the servo is on pin 9
}

void loop() 
{
  left = analogRead(inputLeft);
  right = analogRead(inputRight);
  
  if (left > (right + 20)) { // the +20 is a buffer to stop it for just jiggling around
    pos--;
    myservo.write(pos); // tell servo to move towards the right
    delay(10);
  }
  else if (right > (left + 20)) {
    pos++;
    myservo.write(pos); // tell servo to move towards the left
    delay(10);
  }
  else {
    // do nothing
  }
}

Put in some Serial.print() statements so you can see what values are getting into the variables left and right.

Have you a shield between the two sensors so the sun casts a shadow on one of them?

What sensors are you using? How are they wired - make a drawing of all the connections and post a photo of the drawing.

...R

If you can, see what happens if you put a 2" or 3" tube on the light sensors. It should help to make for a more pronounced reading from the sensors.

I think you need to change the '// do nothing' to code that will actually stop the motor.
its probably not enough to just stop changing 'pos' once the sensor readings more or less balance.

Reply #3 prompts me to ask are you using a continuous rotation servo? I had assumed you are using a regular servo.

If you are using a continuous rotation servo you must actively set the correct servo.write() (or better servo.writeMicroseconds() ) value to ensure it stops.

...R

Thank you for your help. I'll try all your suggestions. :slight_smile: :slight_smile: :slight_smile: