How to create Class and Object on Arduino IDE?

I want to do OOP (Object Oriented Programming) on Arduino. How to create Class and Object on Arduino IDE? For example, I want to create a class to control LED.

Answer

There are two ways to create and use Class on Arduino.

The rest of this will show how to create Class in the same folder with Arduino sketch.

Let's assump that we want to create a class, called LED, to do the following works:

Let's do it step by step:

// LED.h #ifndef LED_h #define LED_h #include <Arduino.h> class LED { private: int ledPin; unsigned char ledState; public: LED(int pin); void turnON(); void turnOFF(); int getState(); }; #endif
// LED.cpp #include "LED.h" LED::LED(int pin) { ledPin = pin; ledState = LOW; pinMode(ledPin, OUTPUT); } void LED::turnON() { ledState = HIGH; digitalWrite(ledPin, ledState); } void LED::turnOFF() { ledState = LOW; digitalWrite(ledPin, ledState); } int LED::getState() { return ledState; }
// main code: ArduinoCode.ino #include "LED.h" LED led1(2); // create a LED object that attach to pin 2 LED led2(3); // create a LED object that attach to pin 3 void setup() { Serial.begin(9600); } void loop() { led1.turnON(); led2.turnON(); Serial.print("LED 1 state: "); Serial.println(led1.getState()); Serial.print("LED 2 state: "); Serial.println(led2.getState()); delay(2000); led1.turnOFF(); led2.turnOFF(); Serial.print("LED 1 state: "); Serial.println(led1.getState()); Serial.print("LED 2 state: "); Serial.println(led2.getState()); delay(2000); }

Now you will see three files in three tab on Arduino IDE:

※ NOTE THAT:

Because the class files (LED.h and LED.cpp) are stored in the same folder as main sketch (ArduinoCode.ino), You need to call #include "LED.h", not #include <LED.h>

Test the class and object by:

※ NOTE THAT:

The above code is a simple LED class. You can refer to our Arduino - LED library to learn more

See more references:

Buy Arduino

1 × Arduino UNO Buy on Amazon
1 × USB 2.0 cable type A/B Buy on Amazon
1 × Jumper Wires Buy on Amazon
Please note: These are affiliate links. If you buy the components through these links, We may get a commission at no extra cost to you. We appreciate it.

The Best Arduino Starter Kit

※ OUR MESSAGES