Uniostar
Published © GPL3+

Arduino PID Tutorial - Solar Tracker

Maximize solar efficiency with an Arduino-based PID solar tracker that intelligently aligns panels for optimal sun exposure.

IntermediateFull instructions provided1 hour254
Arduino PID Tutorial - Solar Tracker

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
LDR, 5 Mohm
LDR, 5 Mohm
×2
Resistor 1k ohm
Resistor 1k ohm
×2
Jumper wires (generic)
Jumper wires (generic)
×1
SG90 Micro-servo motor
SG90 Micro-servo motor
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Schematics

Schematic

Code

Main Code

Arduino
#include <Servo.h>

Servo rotator;

// PID variables
float target = 0;
float current = 0;
float error = 0;
float prevError = 0;
float integral = 0;
float derivative = 0;

// PID Gains
float Kp = 0.01;
float Ki = 0.002;
float Kd = 0.015;

float currentServoAngle = 90;

unsigned long lastTime = 0;

void setup() 
{
  Serial.begin(9600);
  rotator.attach(9);
  rotator.write(90);
  lastTime = millis();
  delay(2000);
}

void loop() 
{
  unsigned long now = millis();
  float deltaTime = (now - lastTime) / 1000.0;
  lastTime = now;

  int left = smoothen(20, A1);
  int right = smoothen(20, A0);
  current = left - right;

  error = target - current;

  if (abs(error) < 5) integral = 0;

  integral += error * deltaTime;
  integral = constrain(integral, -100, 100); 
  derivative = (error - prevError) / deltaTime;

  float output = Kp * error + Ki * integral + Kd * derivative;

  currentServoAngle += output;
  currentServoAngle = constrain(currentServoAngle, 0, 180);

  rotator.write((int) currentServoAngle);

  prevError = error;

  Serial.print("Error: ");
  Serial.print(error);
  Serial.print("\tOutput: ");
  Serial.println(output);

  delay(100);
}

int smoothen(int arraySize, int inputPin) 
{
  long sum = 0;

  for (int i = 0; i < arraySize; i++) 
  {
    sum += map(analogRead(inputPin), 0, 675, 0, 1000);
  }

  return sum / arraySize;
}

Credits

Uniostar
10 projects • 8 followers
Electrical Engineering Undergrad Student specialized in low-level programming, IoT projects, and microcontroller electronics.

Comments