Skip to content

Instantly share code, notes, and snippets.

@todocono todocono/solar-panel.ino
Last active Oct 12, 2017

What would you like to do?
This is a mesh of code examples from Arduino Servo and AnalogInOutSerial
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:
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:
case 1:
case 3:
// print the results to the Serial Monitor:
Serial.print("Status is ");
Serial.print(", \t Light measures is: ");
// wait 2 milliseconds before the next loop for the analog-to-digital
// converter to settle after the last reading:
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:
Serial.print("Moving the servo to the position: ");
void night(void) {
void sunrise(void) {
//follow very slowly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.