How to use C++ Classes in Arduino IDE without creating a Library

If you looked inside an Arduino Library you would see filename extensions such as .h and .cpp, which makes us conclude that the Arduino IDE uses C++ for its codes. If you look inside those files most of the Arduino Libraries have C++ classes inside of them. The question now is: Can you use C++ Classes in Arduino IDE without Creating a Library?

The answer to that is YES!

It is a bit tricky as there are rules you need to follow. I shall dive into that later.

Sample Code

Below is a short Arduino Code with a C++ Class without using a Library.

#define PIN_LED1 3
#define PIN_LED2 4
#define PIN_LED3 5
#define PIN_LED4 6

/*
 * BLINKER CLASS DEFINITION
 */
class Blinker {
  private:
    byte pinLED;

    boolean ledState = LOW;

    unsigned long timeLedOn;
    unsigned long timeLedOff;

    unsigned long nextChangeTime = 0;

  public:
    Blinker(byte pinLED, unsigned long timeLedOn, unsigned long timeLedOff) {
      this->pinLED = pinLED;
      this->timeLedOn = timeLedOn;
      this->timeLedOff = timeLedOff;

      pinMode(pinLED, OUTPUT);
    }

    // Checks whether it is time to turn on or off the LED.
    void check() {
      unsigned long currentTime = millis();

      if(currentTime >= nextChangeTime) {

        if(ledState) {
          // LED is currently turned On. Turn Off LED.
          ledState = LOW;
          nextChangeTime = currentTime + timeLedOff;
        }
        else{
          // LED is currently turned Off. Turn On LED.
          ledState = HIGH;
          nextChangeTime = currentTime + timeLedOn;
        }

        digitalWrite(pinLED, ledState);
      }
    }
};

/*
 *  BLINKER CLASS VARIABLES DECLARATION
 */
Blinker blink1 = Blinker(PIN_LED1, 500, 500);
Blinker blink2 = Blinker(PIN_LED2, 1000, 1000);
Blinker blink3 = Blinker(PIN_LED3, 2000, 2000);
Blinker blink4 = Blinker(PIN_LED4, 1000, 2000);

void setup() {

}

void loop() {
  blink1.check();
  blink2.check();
  blink3.check();
  blink4.check();
}

Okay, I admit that was not very short. At least you can see that I have used a C++ Class without creating a library. You can compile it in your Arduino IDE if you still do not believe me. You can see the Circuit Diagram somewhere below, there is also a Fritzing Diagram if you want to seriously test it.

You can check the code in my Github here.

Continue reading How to use C++ Classes in Arduino IDE without creating a Library