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 (version 1.x and 2.x)? 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:

Arduino IDE adds file
Arduino IDE adds h file
// 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
Arduino IDE adds cpp file
// 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: ArduinoGetStarted.com.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:

Arduino IDE adds cpp file

※ NOTE THAT:

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

Test the class and object by:

COM6
Send
LED 1 state: 1 LED 2 state: 1 LED 1 state: 0 LED 2 state: 0 LED 1 state: 1 LED 2 state: 1 LED 1 state: 0 LED 2 state: 0
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

※ 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 Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

The Best Arduino Starter Kit

※ OUR MESSAGES