Created
October 23, 2016 18:05
-
-
Save chetankothari/d6ae6766861c046081d9b56b6a62275d to your computer and use it in GitHub Desktop.
Dual axis sun tracker using three LDR and Arduino Uno
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Servo.h> | |
#define NUM_PINS 3 | |
int sensorPins[NUM_PINS] = {A0, A1, A2}; | |
int sensorValues[NUM_PINS] = {0, 0, 0}; | |
Servo lrservo; | |
Servo tbservo; | |
int inPin = 7; | |
int ledPin = 13; | |
void setup() { | |
Serial.begin(9600); //sets serial port for communication | |
lrservo.attach(10, 544, 2260); // attaches the servo on pin 9 to the servo object | |
tbservo.attach(9, 544, 2260); // attaches the servo on pin 9 to the servo object | |
lrservo.write(90); | |
tbservo.write(90); | |
pinMode(ledPin, OUTPUT); | |
} | |
char str[1024]; | |
int lrangle = 90; | |
int tbangle = 90; | |
void readInputs() { | |
for (int i = 0; i < NUM_PINS; i++) { | |
sensorValues[i] = sensorValues[i] * 0.6 + analogRead(sensorPins[i]) * 0.4; | |
// sensorValues[i] = analogRead(sensorPins[i]) * 0.5; | |
} | |
//sprintf(str, "%f %f %f", sensorValues[0], sensorValues[1], sensorValues[2]); | |
Serial.println(str); | |
} | |
void calibrate() { | |
digitalWrite(ledPin, HIGH); | |
readInputs(); | |
} | |
int getAngle(int a, int b, int init, int fast, int min, int max) { | |
int angle = init; | |
if (a < b) { | |
angle += (b - a) > 20 ? fast : (b - a) > 4 ? fast / 2 : 0; | |
} else { | |
angle -= (a - b) > 20 ? fast : (a - b) > 4 ? fast / 2 : 0; | |
} | |
if (angle < min) { | |
angle = min; | |
} else if (angle > max) { | |
angle = max; | |
} | |
return angle; | |
} | |
int loopCount = 0; | |
void operate() { | |
digitalWrite(ledPin, LOW); | |
loopCount++; | |
//if (loopCount % 2 == 0) { | |
readInputs(); | |
//} else { | |
int top = sensorValues[1]; | |
int bottom = sensorValues[2]; | |
int left = sensorValues[0]; | |
int right = (sensorValues[1] + sensorValues[2]) / 2; | |
tbangle = getAngle(top, bottom, tbangle, 8, 30, 170); | |
lrangle = getAngle(left, right, lrangle, 8, 20, 160); | |
sprintf(str, "%d %d %d, TB : %d %d, LR: %d %d lrangle: %d, tbangle: %d", sensorValues[0], sensorValues[1], sensorValues[2], top, bottom, left, right, lrangle, tbangle); | |
Serial.println(str); | |
lrservo.write(lrangle); | |
tbservo.write(tbangle); | |
//} | |
} | |
void loop() { | |
if (millis() < 10) { | |
calibrate(); | |
} else { | |
operate(); | |
} | |
delay(5); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment