Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ViliusKraujutis
Created May 7, 2016 23:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ViliusKraujutis/955cc62cad4242be2c6bc4740e100a1c to your computer and use it in GitHub Desktop.
Save ViliusKraujutis/955cc62cad4242be2c6bc4740e100a1c to your computer and use it in GitHub Desktop.
Arduino Nano + 9V battery + M-1503 Servo = panoramic timelapse rotator-phone holder.
#include <Servo.h>
float TIMELAPSE_SPEED = 5; // N:1
long COOLDOWN = 2000 * TIMELAPSE_SPEED;
long CYCLE = 20000 * TIMELAPSE_SPEED;
long ANGLE_MIN = 45;
long ANGLE_MAX = 135;
long angleRange = ANGLE_MAX - ANGLE_MIN;
long LED_FLASH_RATIO_1 = 500;
long LED_FLASH_RATIO_2 = 1000;
Servo myservo;
int pinLED = 13;
int pinServo = 11;
int pos = 0; // variable to store the servo position
int lastPos = 0;
long msec = 0;
double ms = 0;
void setup() {
pinMode(pinLED, OUTPUT);
myservo.attach(pinServo); // attaches the servo on pin 9 to the servo object
servoWrite(ANGLE_MAX);
Serial.begin(9600);
}
void loop() {
msec = millis() % (2*CYCLE + 2*COOLDOWN);
if (msec < COOLDOWN || (COOLDOWN + CYCLE < msec && msec < COOLDOWN*2 + CYCLE)) {
flashLed(msec, LED_FLASH_RATIO_1);
Serial.println("Cooldown");
return;
}
flashLed(msec, LED_FLASH_RATIO_2);
rotateServo(msec);
}
void flashLed(int currentMillis, int ratio) {
if (currentMillis % ratio < ratio / 2) {
digitalWrite(pinLED, HIGH); // turn the LED on (HIGH is the voltage level)
} else {
digitalWrite(pinLED, LOW); // turn the LED off by making the voltage LOW
}
}
void rotateServo(double msec) {
if(msec < COOLDOWN + CYCLE) {
msec = msec - COOLDOWN;
pos = ANGLE_MIN + (CYCLE-msec)/CYCLE*angleRange;
} else {
msec = msec - COOLDOWN - CYCLE - COOLDOWN;
pos = ANGLE_MIN + msec/CYCLE*angleRange;
}
if(lastPos == pos) return;
lastPos = pos;
servoWrite(pos);
}
void servoWrite(int pos) {
pos = minMaxVal(pos, ANGLE_MIN, ANGLE_MAX);
Serial.print("Servo.write: ");
Serial.println(pos);
myservo.write(pos); // tell servo to go to position in variable 'pos'
}
int minMaxVal(int val, int minimum, int maximum) {
return min(max(val, minimum), maximum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment