/*
  Solar Tracker

  Controls two relays which will rotate solar panel stand to sun.

  The circuit:
  - Relay controls taken from Digital 12 and 13
  - Two pushbuttons attached to Digital pin 2 and 3 from +5V
  - 10K resistor attached to Digital pin 2 and 3 from ground
  - Two LDR resistors connected to Analog inputs A0 and A1

*/
#include <Wire.h>

// constants won't change. They're used here to set pin numbers:
const int buttonPinL = 2;  // number of Left switch
const int buttonPinR = 15;  // number of Right switch
const int relayPinL = 16;  // the number of the relay Left
const int relayPinR = 17;  //the number of the relay Right
// LDR and button pin connections
// name = analogpin;

const int ldrL = 34;  //LDR left nascer do sol
const int ldrR = 35;  //LDR right por do sol


// variables will change:
int buttonState = 0;  // variable for reading the pushbutton status

void setup() {

  // initialize the Relay pin as an output:
  Serial.begin(9600);
  pinMode(relayPinR, OUTPUT);
  pinMode(relayPinL, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPinL, INPUT);
  pinMode(buttonPinR, INPUT);
}

void loop() {
  // read the state of the pushbutton L value:
  buttonState = digitalRead(buttonPinL);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn Relay on:
    digitalWrite(relayPinL, HIGH);
  } else {
    // turn Relay off:
    digitalWrite(relayPinL, LOW);
  }

  // read the state of the pushbutton R value:
  buttonState = digitalRead(buttonPinR);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn Relay on:
    digitalWrite(relayPinR, HIGH);
  } else {
    // turn Relay off:
    digitalWrite(relayPinR, LOW);
  }

  int left = analogRead(ldrL);   // left
  int right = analogRead(ldrR);  // right
  Serial.print("POR DO SOL LDR1 = ");
  Serial.println(right);
  Serial.print("NASCER DO SOL LDR2 = ");
  Serial.println(left);


  const int tol = 80;  //tolerance between LDR readings

  int dhoriz = left - right;  // check the diffirence between left and rigt


  if (-tol > dhoriz || dhoriz > tol) {
    // difference in horizontal is great enough to act on
    if (left > right) {
      // resistance on left is greater than on right
      digitalWrite(relayPinL, LOW);
      digitalWrite(relayPinR, HIGH);
      Serial.print("MOTOR NASCER DO SOL");
    } else {
      // resistance on right is greater than on left
      digitalWrite(relayPinR, LOW);
      digitalWrite(relayPinL, HIGH);
      Serial.print("MOTOR  POR DO SOL");
      
    }
  } else {
    //difference in horizontal is below tolerance
    digitalWrite(relayPinL, LOW);
    digitalWrite(relayPinR, LOW);
    Serial.print("MOTOR PARADO");
  }

  // Wait a second before checking again
  delay(3000);
}
NOCOMNCVCCGNDINLED1PWRRelay Module
NOCOMNCVCCGNDINLED1PWRRelay Module