I am trying to make a Dual Axis Solar tracker using 4 LDRs, 2 Servo Motors and Arduino Leonardo... the +5 pins of each motor is connected with a +5 pin of voltage regulator and external 12v battery . However, it does not work .. both motors have some random movements but they dont work as i was expecting them to. I am not sure if theres something wrong with my PCB circuit or with my code. Can you please have a look at my code and tell if its right ? Following is my code which i think is right but i am not sure
Code: Select all
#include <Servo.h>
Servo horizontal;
int servoh = 90; //defining horzontal motor with initial position 90
Servo vertical;
int servov = 90; //defining vertical motor with initial position 90
const int ldrTopL = 0;
const int ldrTopR = 1;
const int ldrBottomL = 2;
const int ldrBottomR = 3; //defining teh pins of LDRs on arduino
void setup()
{
Serial.begin(9600);
horizontal.attach(5);//horizontal servo attached to pin 5 of arduino
horizontal.write(servoh);//sending the signal to the motor to set it to its initial position
vertical.attach(6);//vertical servo attached to pin 6 of arduino
vertical.write(servov);//sending the signal to the motor to set it to its initial position
pinMode(ldrTopL, INPUT);
pinMode(ldrTopR, INPUT);
pinMode(ldrBottomL, INPUT);
pinMode(ldrBottomR, INPUT); //setting the LDRs as input
pinMode(servoh, OUTPUT);
pinMode(servov, OUTPUT);//i am not sure about this part but i included them anyway.. setting the SERVOs as outputs
}
void loop()
{
int TopL = analogRead(ldrTopL);
int TopR = analogRead(ldrTopR);
int BottomL = analogRead(ldrBottomL);
int BottomR = analogRead(ldrBottomR);//Taking the readings of each LDR with a delay of 10 ms
delay(10);
int avTOP = (TopL + TopR) / 2;
int avBottom = (BottomL + BottomR) / 2;
int avLEFT = (TopL + BottomL) / 2;
int avRIGHT = (TopR + BottomR) / 2; //my Ldrs will placed between + shaped barriers so the top side will contain top right and top left LDRs i have included the picture of my panel
Serial.println(avTOP);
Serial.println(avBottom);
Serial.println(avLEFT);
Serial.println(avRIGHT);
if (avTOP > avBottom)
{
vertical.write(servov += 1);
delay(10);
if (servov > 180)
{
vertical.write(servov = 180);
delay(10);
}
}
else if (avTOP < avBottom)
{
vertical.write(servov -= 1);
delay(10);
if (servov < 0)
{
vertical.write(servov = 0);
delay(10);
}
}
if (avLEFT > avRIGHT)
{
horizontal.write(servoh -= 1);
delay(10);
if (servoh < 0)
{
horizontal.write(servoh = 0);
delay(10);
}
}
else if (avLEFT < avRIGHT)
{
horizontal.write(servoh += 1);
delay(10);
if (servoh > 180)
{
horizontal.write(servoh = 180);
delay(10);
}
}
else if (avLEFT == avRIGHT)
{
//if the average is equal do nothing
}
}