Advertisement
Guest User

C++ arduino code for the solar tracker

a guest
Feb 7th, 2016
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. #include <Servo.h> // include Servo library
  2.  
  3. Servo horizontal; // horizontal servo
  4. int servoh = 90; // stand horizontal servo SET SERVO POSITIONS VARIABLES TO MID-POINT
  5. Servo vertical; // vertical servo
  6. int servov = 90; // stand vertical servo
  7.  
  8. // LDR pin connections
  9. // name = analogpin; defining LDR input pin names+attaching to physical pins
  10. int ldrLT = 0; //LDR top left
  11. int ldrRT = 1; //LDR top right
  12. int ldrLD = 2; //LDR down left
  13. int ldrRD = 3; //ldr down right
  14.  
  15. void setup()
  16. {
  17. Serial.begin(9600); //opens serial port, sets data rate to 9600 bits/s
  18. // servo connections
  19. // name.attach(pin);
  20. horizontal.attach(9); //attach physical digital pins to servos (PWM~ pins 9 and 10)
  21. vertical.attach(10);
  22. }
  23.  
  24. void loop()
  25. {
  26. int LeftTop = analogRead(ldrLT); // top left
  27. int RightTop = analogRead(ldrRT); // top right
  28. int LeftDown = analogRead(ldrLD); // down left
  29. int RightDown = analogRead(ldrRD); // down right
  30.  
  31. int dtime = analogRead(4)/20; // read potentiometers - dtime is for how often to check difference
  32. int tol = analogRead(5)/4; //read potentiometers - tol is tolerance for how far off the LDRs can be
  33.  
  34. int avt = (LeftTop + RightTop) / 2; // average value top
  35. int avd = (LeftDown + RightDown) / 2; // average value down
  36. int avl = (LeftTop + LeftDown) / 2; // average value left
  37. int avr = (RightTop + RightDown) / 2; // average value right
  38.  
  39. int dvert = avt - avd; // check the difference of up and down
  40. int dhoriz = avl - avr;// check the difference of left and right
  41.  
  42. if (-1*tol > dvert || dvert > tol) // check if the diffirence is within the tolerance else change vertical angle
  43. {
  44. if (avt > avd)
  45. {
  46. servov = ++servov;
  47. if (servov > 180)
  48. {
  49. servov = 180;
  50. }
  51. }
  52. else if (avt < avd)
  53. {
  54. servov= --servov;
  55. if (servov < 0)
  56. {
  57. servov = 0;
  58. }
  59. }
  60. vertical.write(servov);
  61. }
  62.  
  63. if (-1*tol > dhoriz || dhoriz > tol) // check if the diffirence is within the tolerance else change horizontal angle
  64. {
  65. if (avl > avr)
  66. {
  67. servoh = --servoh;
  68. if (servoh < 0)
  69. {
  70. servoh = 0;
  71. }
  72. }
  73. else if (avl < avr)
  74. {
  75. servoh = ++servoh;
  76. if (servoh > 180)
  77. {
  78. servoh = 180;
  79. }
  80. }
  81. else if (avl == avr)
  82. {
  83. // nothing
  84. }
  85. horizontal.write(servoh);
  86. }
  87. delay(dtime);
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement