CYTHEIA AIOpen the editor

Blinking Objects

Three LEDs blink at three speeds at once, each looked after by its own object, with no delay() anywhere.

Open this circuit and run it

Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.

How it works

Three LEDs, each with its own resistor, are wired to pins 11, 12 and 13, just as in the Traffic Light. What is new is how the code is organised. A class is a blueprint that bundles information (here which pin, how often to blink, whether the LED is on, and when it last changed) together with the functions that work on it. Each Blinker object made from the blueprint looks after one LED.

Blinker(11, 250) creates an object for pin 11 that changes every 250 milliseconds; the constructor stores those two numbers. begin() makes the pin an output, and update() is the whole behaviour: it reads millis(), and once the interval has passed since lastChange it flips isOn, writes the pin and notes the time. Nothing ever waits, so the three objects, kept together in the array blinkers, can be updated one after another in loop(), thousands of times a second, and each LED blinks at its own pace: every 250, 500 and 1000 milliseconds. The Traffic Light uses delay() and can only do one thing at a time. The word private: marks the data that only the object’s own functions may touch, and public: marks what the rest of the sketch can call. The Serial tab shows each time an LED turns on.

Parts

Wiring

Arduino code

// Blinking Objects
// A class bundles information (which pin, how often to blink, whether the LED
// is on) together with the functions that use it. Each Blinker looks after
// one LED on its own timer, so three LEDs blink at three speeds at once
// without a single delay().
class Blinker {
  private:
    int pin;
    unsigned long interval;
    unsigned long lastChange;
    bool isOn;

  public:
    Blinker(int ledPin, unsigned long blinkEvery) {
      pin = ledPin;
      interval = blinkEvery;
      lastChange = 0;
      isOn = false;
    }

    void begin() {
      pinMode(pin, OUTPUT);
    }

    void update() {
      unsigned long now = millis();
      if (now - lastChange >= interval) {
        lastChange = now;
        isOn = !isOn;
        digitalWrite(pin, isOn ? HIGH : LOW);
        if (isOn) {
          Serial.print("Pin ");
          Serial.print(pin);
          Serial.println(" on");
        }
      }
    }
};

Blinker blinkers[3] = { Blinker(11, 250), Blinker(12, 500), Blinker(13, 1000) };

void setup() {
  Serial.begin(9600);
  for (int i = 0; i < 3; i++) {
    blinkers[i].begin();
  }
}

void loop() {
  for (int i = 0; i < 3; i++) {
    blinkers[i].update();
  }
}

Try changing it

Open this circuit and run it

Next challenge

More projects in LED & Lighting