2 "independent" flickering diodes

Here is a simple C++ class example I wrote a couple of years ago. You would need to modify it a bit for different on and off times. It allows multiple blinking objects.

/*
 * Blink
 *
 * Blink using a c++ class to toggle pin 
 * Each time the toggle member function is called a 
 *  check is done to see if it is time to toggle yet
 */
 /* ==================================== */
// Interface description - this must be first and would
//  normally be in a header file as part of a library
class TogglePin {
  public:
    // constructors:
    TogglePin(byte inPinNumber);
    TogglePin(byte inPinNumber, unsigned long inDelayTime);

    // delay setter method:
    void setDelay(unsigned long inDelayTime);

    // doit method:
    void toggle(void);

   private:
 
    // minimize chances for user to screw up 
     TogglePin (const  TogglePin& a);              // disallow copy constructor
     TogglePin & operator=(const  TogglePin& a);   // disallow assignment operator
     
    // object data 
    byte pinState;            // current pin state
    byte pinNumber;           // pin to use
    unsigned long delayTime;  // delay in ms
    unsigned long currentMs;  // current ms count
    unsigned long testMs;     // test ms 
};   // end TogglePin class definition


// Implementation - this would normally be in a .cpp
//   file as part of a library
TogglePin::TogglePin(byte inPinNumber)
{
  pinMode(inPinNumber, OUTPUT);   // sets the digital pin as output
  pinState=HIGH;
  pinNumber=inPinNumber;
  delayTime=1000;
  testMs=millis();
}
TogglePin::TogglePin(byte inPinNumber, unsigned long inDelayTime)
{
  pinMode(inPinNumber, OUTPUT);   // sets the digital pin as output
  pinState=HIGH;
  pinNumber=inPinNumber;
  delayTime=inDelayTime;
  testMs=millis();
}
void TogglePin::setDelay(unsigned long inDelayTime)
{
  delayTime=inDelayTime;
}
void TogglePin::toggle(void)
{
  currentMs=millis();
  if((currentMs-testMs)>=delayTime) {
    //delay is up
    pinState^=1;                      //toggle state
    digitalWrite(pinNumber,pinState); // write new pin value
    testMs=currentMs;
  } 
}
/* ==================================== */

/* ********************* Start Demo Code **/  

byte blinkPin1 = 12;     // LED connected to digital pin 12
byte blinkPin2 = 13;     // LED connected to digital pin 13 - onboard LED
TogglePin blink1(blinkPin1);            // default constructor 1 sec delay
TogglePin blink2(blinkPin2,300);        // constructor with 300 ms delay

 void setup()                   
{
    // Move along - nothing to see here
}

void loop()                     // run over and over again
{
  blink1.toggle();
  blink2.toggle();
  // other interesting code here
  // it should take much less than the blink time, otherwise the 
  // blink time will be dependent on the code execution time
}

/* ********************* End Demo Code **/
1 Like