Skip to content

Instantly share code, notes, and snippets.

@eightlines
Last active August 29, 2015 14:19
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 eightlines/4f2b16231b9855d1e367 to your computer and use it in GitHub Desktop.
Save eightlines/4f2b16231b9855d1e367 to your computer and use it in GitHub Desktop.
Rotates a servo while fading the LEDs
#include <Streaming.h>
#include <Servo.h>
#include <Adafruit_NeoPixel.h>
Servo servo; // D9
Adafruit_NeoPixel leds = Adafruit_NeoPixel(15, 7, NEO_GRB + NEO_KHZ800);
unsigned long millisServo = 0;
unsigned long millisLed = 0;
unsigned long millisLedFade = 0;
int delayServo = 100;
int delayLed = 3000;
int servoPosition = 0;
int servoDirection = 1;
int servoMax = 180;
int servoMin = 40;
uint32_t colors[3] = {
leds.Color(255, 0, 0),
leds.Color(0, 255, 0),
leds.Color(0, 0, 255)
};
int colorIndex = 0;
uint32_t colorCurrent = 0;
uint8_t
rVal = 0,
gVal = 0,
bVal = 0;
void setup() {
Serial.begin(9600);
Serial << "Init" << endl;
leds.begin();
leds.show();
servo.attach(9);
millisServo = millis();
millisLed = millis();
millisLedFade = millis();
}
void loop() {
unsigned long millisCurrent = millis();
if (millisCurrent - millisServo > delayServo) {
millisServo = millisCurrent;
servoPosition += servoDirection;
if (servoDirection == 1 &&
servoPosition >= servoMax) {
servoDirection *= -1;
} else if (servoDirection == -1 &&
servoPosition < servoMin) {
servoDirection *= -1;
}
Serial << "Servo Position: " << servoPosition << endl;
servo.write(servoPosition);
}
if (millisCurrent - millisLed > delayLed) {
millisLed = millisCurrent;
colorIndex ++;
if (colorIndex >= 3) colorIndex = 0;
}
fade(colors[colorIndex]);
}
void fade(uint32_t color) {
uint8_t toR = (color & 0xFF0000) >> 16;
uint8_t toG = (color & 0x00FF00) >> 8;
uint8_t toB = (color & 0x0000FF);
if (rVal < 256 && rVal >= 0) {
rVal += (rVal < toR) ? 1 : (rVal > toR) ? -1 : 0;
}
if (gVal < 256 && gVal >= 0) {
gVal += (gVal < toG) ? 1 : (gVal > toG) ? -1 : 0;
}
if (bVal < 256 && bVal >= 0) {
bVal += (bVal < toB) ? 1 : (bVal > toB) ? -1 : 0;
}
Serial << toR << "/" << rVal << ", " << toG << "/" << gVal << ", " << toB << "/" << bVal << endl;
for (int j = 0; j < leds.numPixels(); j++) {
leds.setPixelColor(j, leds.Color(rVal, gVal, bVal));
}
leds.show();
}
int channel(uint32_t color, char channel) {
switch (channel) {
case 'r': return (color & 0xFF0000) >> 16; break;
case 'g': return (color & 0x00FF00) >> 8; break;
case 'b': return (color & 0x0000FF); break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment