if you google for “Arduino LED blinking sketch” you might find something like this:

#define ONBOARD_LED  2

void setup() {
  pinMode(ONBOARD_LED,OUTPUT);
}

void loop() {
  delay(1000);
  digitalWrite(ONBOARD_LED,HIGH);
  delay(100);
  digitalWrite(ONBOARD_LED,LOW);
}

(I’am using an ESP32 and therefore I needed to define the ONBOARD_LED because this is not predefined in Arduino.h)

This is basically working but it adds a delay of 1.1 seconds to the loop which might be pretty disastrous if you you have some other time critical functionality which needs to happen in the loop as well.

So a less intrusive implementation is using the time to figure out if led needs to be switched on or off:


#define ONBOARD_LED 2 bool led_state = true; int led_interval = 1000; long led_timeout; void setup() { pinMode(ONBOARD_LED, OUTPUT); } void loop() { // update led if (led_interval>0 && millis()>led_timeout){ led_state = !led_state; led_timeout = millis()+led_interval; digitalWrite(ONBOARD_LED, led_state); } }

You might think about abstracting the functionality in a separate class

// content of LED.h

class LED {
  private:
    int pin;
    bool state;
    int interval;
    long timeout;

  public:
    LED(int pin=2) {
      this->pin = pin;
      pinMode(pin, OUTPUT);
    };

    void setState(boolean on) {
        this->state = on;
        this->timeout = 0;
        digitalWrite(pin,state);
    };

    bool getState() {
      return state;
    };

    void setBlinking(int ms) {
        this->interval = ms;
        this->state = false;
        this->timeout = millis()+interval;
    };

    void update() {
         if (timeout>0 && millis()>timeout){
            state = !state;
            timeout = millis()+interval;
            digitalWrite(pin,state);
         }
    };

};

And then your blinking sketch gets pretty small:

#include "LED.h"
#define ONBOARD_LED  2

LED led(ONBOARD_LED);

void setup() {
  led.setBlinking(1000);
}

void loop() {
  led.update();
}

Summary

I like the concept of using separate classes to abstract the complexity in Arduino Sketches. It also helps to make the Sketches more readable.

In standard C++ it is required that you split the declaration (which is in the .h file) from the implementation (which is in .cpp files). Above I used the shortcut and added the implementation directly into the .h file.

I think that in a Arduino Project you might get away with this. You will definitely need to do this split if you want to publish your code as Arduino Library

Categories: Arduino

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *