#include <Servo.h>
#define BUTTON 6
class Sweeper
{
Servo servo; // the servo
int pos; // current servo position
int increment; // increment to move for each interval
int updateInterval; // interval between updates
unsigned long lastUpdate; // last update of position
public:
Sweeper(int interval)
{
updateInterval = interval;
increment = 1;
}
void Attach(int pin)
{
servo.attach(pin);
}
void Detach()
{
servo.detach();
}
void Update()
{
if ((millis() - lastUpdate) > updateInterval)
{
lastUpdate = millis();
pos +=increment;
servo.write(pos);
if ((pos <= 0) || (pos >= 180))
{
increment = -increment; // Reverse direction
}
}
}
};
class Led
{
// Class Variables
int Ledpin; // The pin to control the LED
int State; // The state of the LED
unsigned long PrevMillis; // Last time the LED was updated
long ONPeriod; // How long the LED will be ON
long OFFPeriod; // How long the LED will be OFF
// Class Constructors
public:
Led(int pin, long on, long off)
{
Ledpin = pin;
ONPeriod = on;
OFFPeriod = off;
// Variables that needs to be passed by refrence
State = LOW;
PrevMillis = 0;
}
// Class Methods
void Update()
{
// Initialize time
unsigned long currentMillis = millis();
if ((State == HIGH) && ((currentMillis - PrevMillis) >= ONPeriod)){
PrevMillis = currentMillis;
State = LOW;
}else if ((State == LOW) && ((currentMillis - PrevMillis) >= OFFPeriod)){
PrevMillis = currentMillis;
State = HIGH;
}
digitalWrite(Ledpin, State);
}
};
// #############################################################################
Sweeper sweeper1(15);
Sweeper sweeper2(15);
Led blueLed(3, 1000, 500);
Led purpleLed(2, 500, 1000);
void setup() {
sweeper1.Attach(4);
sweeper2.Attach(5);
pinMode(BUTTON, INPUT_PULLUP);
}
void loop() {
sweeper1.Update();
purpleLed.Update();
if (digitalRead(BUTTON))
{
sweeper2.Update();
blueLed.Update();
}
}