Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Solar code example
- Example 7
- Introduction to Robotics
- by Rodolfo Cossovich at New York University Shanghai
- Description: Using and LDR to move a servo to simulate a
- solar panel tracking the sun.
- It's meant to illustrate Finite State Machines.
- Strongly inspired in Arduino code examples AnalogInOutSerial and Servo
- */
- #include <Servo.h>
- Servo myservo; // create servo object to control a servo
- // twelve servo objects can be created on most boards
- // These constants won't change. They're used to give names to the pins used:
- const int analogInPin = A0; // Analog input pin that the potentiometer is attached to
- const int analogOutPin = 9; // Analog output pin that the LED is attached to
- int sensorValue = 0; // value read from the pot
- int servoValue = 0; // value output to the PWM (analog out)
- byte state = 0; //default state - unknown previous state neither current sensor values
- void setup() {
- // initialize serial communications at 9600 bps:
- Serial.begin(9600);
- myservo.attach(9); // attaches the servo on pin 9 to the servo object
- }
- void loop() {
- updateState(); //this is where I check the status of the environment
- switch (state) {
- case 0:
- night();
- break;
- case 1:
- day();
- break;
- case 3:
- sunrise();
- break;
- default:
- night();
- }
- // print the results to the Serial Monitor:
- Serial.print("Status is ");
- Serial.print(state);
- Serial.print(", \t Light measures is: ");
- Serial.println(sensorValue);
- // wait 2 milliseconds before the next loop for the analog-to-digital
- // converter to settle after the last reading:
- delay(2);
- }
- void updateState(void) {
- // read the analog in value:
- sensorValue = analogRead(analogInPin);
- if (sensorValue < 600) {
- state = 1;
- } else if (sensorValue > 700) {
- state = 0;
- }
- }
- void day(void) {
- //track the sun
- // map it to the range of the analog out:
- servoValue = map(sensorValue, 0, 1023, 0, 180);
- // change the analog out value:
- myservo.write(servoValue);
- Serial.print("Moving the servo to the position: ");
- Serial.println(servoValue);
- delay(500);
- }
- void night(void) {
- //stop
- }
- void sunrise(void) {
- //follow very slowly
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement