Skip to content

Instantly share code, notes, and snippets.

@scottbez1
Last active September 19, 2023 11:44
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save scottbez1/d68e9048606fb9d0f8a1b374c207c1b5 to your computer and use it in GitHub Desktop.
Save scottbez1/d68e9048606fb9d0f8a1b374c207c1b5 to your computer and use it in GitHub Desktop.
Example code to animate the eye movements of a pumpkin Halloween decoration. See https://youtu.be/tyLo3LW5UCo for the full build video! Consider sponsoring me on github to support projects like this: https://github.com/sponsors/scottbez1
#include <Servo.h>
Servo s;
int pos[] = { 90, 80, 65, 120, 105, 110, 98, 68, 84, 74};
int d[] = {3000, 500, 1200, 1530, 700, 200, 800, 450, 300, 670};
void setup() {
s.attach(6); // <---- Change 6 to the pin you're using
}
void loop() {
for (int i = 0; i < 10; i++) {
s.write(pos[i]);
delay(d[i]);
}
}
// This code is public domain. Use it however you'd like. Attribution
// to Scott Bezek and the build video (https://youtu.be/tyLo3LW5UCo)
// is always appreciated.
#include <Arduino.h>
#include <Servo.h>
// This is a more advanced example that avoids using delay() so that you can do
// other things while the motor animation is running. In this case, I've added
// a basic LED blink throughout the animation. Pin 17 is one of the built-in
// LEDs on the Pro Micro, but you can change to pin 13 for an Uno.
#define SERVO_PIN 6
#define LED_PIN 17
Servo s;
void setup() {
s.attach(SERVO_PIN);
pinMode(LED_PIN, OUTPUT);
}
unsigned int animationStep = 0;
unsigned long lastAnimationMillis = 0;
int pos[] = { 90, 80, 65, 120, 105, 110, 98, 68, 84, 74};
unsigned long d[] = {3000, 500, 1200, 1530, 700, 200, 800, 450, 300, 670};
// Concurrent blink example:
unsigned long lastBlinkMillis = 0;
bool ledOn = false;
void loop() {
// Check if it's time for the next animation step
if (millis() - lastAnimationMillis > d[animationStep]) {
// It's time to animate! Make a note of the current time that we're running this animation
lastAnimationMillis = millis();
// Move to the next animation step
animationStep++;
// If we've gone through all animation steps, restart at step 0
if (animationStep >= sizeof(pos)/sizeof(pos[0])) {
animationStep = 0;
}
// Move the servo to the new position for this step
s.write(pos[animationStep]);
}
// Check if it's time to blink the LED
if (millis() - lastBlinkMillis > 1000) {
lastBlinkMillis = millis();
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn);
}
}
// This code is public domain. Use it however you'd like. Attribution
// to Scott Bezek and the build video (https://youtu.be/tyLo3LW5UCo)
// is always appreciated.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment