SHARE
TWEET

Untitled

a guest Oct 12th, 2017 45 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.   Solar code example
  3.  
  4.  
  5.   Example 7
  6.    Introduction to Robotics
  7.    by Rodolfo Cossovich at New York University Shanghai
  8.    Description: Using and LDR to move a servo to simulate a
  9.    solar panel tracking the sun.
  10.  
  11.    It's meant to illustrate Finite State Machines.
  12.  
  13.  
  14.   Strongly inspired in Arduino code examples AnalogInOutSerial and Servo
  15.  
  16. */
  17.  
  18.  
  19. #include <Servo.h>
  20.  
  21. Servo myservo;  // create servo object to control a servo
  22. // twelve servo objects can be created on most boards
  23.  
  24. // These constants won't change. They're used to give names to the pins used:
  25. const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
  26. const int analogOutPin = 9; // Analog output pin that the LED is attached to
  27.  
  28. int sensorValue = 0;        // value read from the pot
  29. int servoValue = 0;        // value output to the PWM (analog out)
  30.  
  31. byte state = 0; //default state - unknown previous state neither current sensor values
  32.  
  33. void setup() {
  34.   // initialize serial communications at 9600 bps:
  35.   Serial.begin(9600);
  36.   myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  37. }
  38.  
  39. void loop() {
  40.   updateState();      //this is where I check the status of the environment
  41.  
  42.   switch (state) {
  43.     case 0:
  44.       night();
  45.       break;
  46.     case 1:
  47.       day();
  48.       break;
  49.     case 3:
  50.       sunrise();
  51.       break;
  52.     default:
  53.       night();
  54.   }
  55.  
  56.   // print the results to the Serial Monitor:
  57.   Serial.print("Status is ");
  58.   Serial.print(state);
  59.   Serial.print(", \t Light measures is: ");
  60.   Serial.println(sensorValue);
  61.  
  62.   // wait 2 milliseconds before the next loop for the analog-to-digital
  63.   // converter to settle after the last reading:
  64.   delay(2);
  65. }
  66.  
  67. void updateState(void) {
  68.   // read the analog in value:
  69.   sensorValue = analogRead(analogInPin);
  70.  
  71.   if (sensorValue < 600) {
  72.     state = 1;
  73.   } else if (sensorValue > 700) {
  74.     state = 0;
  75.   }
  76. }
  77.  
  78.  
  79.  
  80. void day(void) {
  81.   //track the sun
  82.   // map it to the range of the analog out:
  83.   servoValue = map(sensorValue, 0, 1023, 0, 180);
  84.   // change the analog out value:
  85.   myservo.write(servoValue);
  86.   Serial.print("Moving the servo to the position: ");
  87.   Serial.println(servoValue);
  88.   delay(500);
  89. }
  90.  
  91. void night(void) {
  92.   //stop
  93. }
  94.  
  95.  
  96. void sunrise(void) {
  97.   //follow very slowly
  98. }
RAW Paste Data
Top