Skip to content

Instantly share code, notes, and snippets.

@GreenMoonArt
Created December 10, 2016 13:02
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 GreenMoonArt/3835b7dfcaf5a7f01f5e4eea23e5ca26 to your computer and use it in GitHub Desktop.
Save GreenMoonArt/3835b7dfcaf5a7f01f5e4eea23e5ca26 to your computer and use it in GitHub Desktop.
// continuously move a servo while an RGB LED continuously updates its color
#include <Servo.h>
Servo servo;
const int servoRestPosition = 0; //Starting position
const int servo90Position = 90; //90 degrees
const int servoTargetPosition = 180; //Position when event is detected
#define GREEN 3
#define BLUE 5
#define RED 6
#define delayTime 20
void setup() {
Serial.begin(9600);
Serial.println("start");
servo.attach(9);
servo.write(servoRestPosition);
analogWrite(RED, 0);
analogWrite(GREEN, 0);
analogWrite(BLUE, 0);
delay(250);
}
int currentServoPosition = 0; // keep track of servo position
int inc_dec = 1; // use to increment/decrement servo position
void loop() {
int redVal = 255;
int blueVal = 0;
int greenVal = 0;
for( int i = 0 ; i < 255 ; i += 1 )
{
greenVal += 1;
redVal -= 1;
analogWrite(GREEN, 255 - greenVal );
analogWrite(RED, 255 - redVal );
updateServoPosition(i);
delay( delayTime );
}
redVal = 0;
blueVal = 0;
greenVal = 255;
for( int i = 0 ; i < 255 ; i += 1 )
{
blueVal += 1;
greenVal -= 1;
analogWrite(BLUE, 255 - blueVal );
analogWrite(GREEN, 255 - greenVal );
updateServoPosition(i);
delay( delayTime );
}
redVal = 0;
blueVal = 255;
greenVal = 0;
for( int i = 0 ; i < 255 ; i += 1 )
{
redVal += 1;
blueVal -= 1;
analogWrite(RED, 255 - redVal );
analogWrite(BLUE, 255 - blueVal );
updateServoPosition(i);
delay( delayTime );
}
} //loop()
void updateServoPosition(int i)
{
if( i % 2 == 0 ) // if i is an even number, then we will move the servo by 1 degree
// arbitrarily decided to update at this frequency
// adjust to your own preferences
{
servo.write(currentServoPosition);
currentServoPosition = currentServoPosition + inc_dec;
//reverse direction upon reachin servo limits
if ( currentServoPosition >= 180 )
{ inc_dec = -1; }
else if( currentServoPosition <= 0 )
{ inc_dec = 1; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment