// Single Axis Solar Tracker using L298N & LDR Modules
const int LDR_North = A1; // LDR facing North
const int LDR_South = A2; // LDR facing South
const int forward = 9; // L298N Forward pin (piston extends)
const int backward = 8; // L298N Backward pin (piston retracts)
const int speedpin = 10; // PWM Speed control for piston
const int threshold = 50; // Light difference threshold for movement
const int sunsetThreshold = 20; // Light level below which tracker resets
void setup() {
Serial.begin(9600);
pinMode(forward, OUTPUT);
pinMode(backward, OUTPUT);
pinMode(speedpin, OUTPUT);
}
void loop() {
int lightNorth = analogRead(LDR_North);
int lightSouth = analogRead(LDR_South);
Serial.print("LDR North: ");
Serial.println(lightNorth);
Serial.print("LDR South: ");
Serial.println(lightSouth);
int luxDiff = lightNorth - lightSouth;
int speed = map(abs(luxDiff), 0, 500, 0, 200);
speed = constrain(speed, 100, 200); // Slow movement speed
// Move tracker based on light difference
if (luxDiff > threshold) {
digitalWrite(forward, HIGH);
digitalWrite(backward, LOW);
analogWrite(speedpin, speed);
}
else if (luxDiff < -threshold) {
digitalWrite(forward, LOW);
digitalWrite(backward, HIGH);
analogWrite(speedpin, speed);
}
else {
digitalWrite(forward, LOW);
digitalWrite(backward, LOW);
analogWrite(speedpin, 0);
}
// Cloud detection (pause if sudden drop in sunlight)
static int previousLux = (lightNorth + lightSouth) / 2;
int currentLux = (lightNorth + lightSouth) / 2;
if (previousLux - currentLux > 100) { // Sudden large drop in sunlight
Serial.println("Cloud detected! Pausing movement...");
digitalWrite(forward, LOW);
digitalWrite(backward, LOW);
analogWrite(speedpin, 0);
delay(30000); // Pause for 30 seconds
}
previousLux = currentLux;
// Return to start position at sunset
if (lightNorth < sunsetThreshold && lightSouth < sunsetThreshold) {
Serial.println("Sunset detected! Returning to start position...");
digitalWrite(forward, LOW);
digitalWrite(backward, HIGH);
analogWrite(speedpin, 150);
delay(5000); // Move for 5 seconds
digitalWrite(backward, LOW);
}
delay(5000); // Delay for 5 seconds to slow down movements
}