Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using classes with the Arduino

I'm trying to use class objects with the Arduino, but I keep running into problems. All I want to do is declare a class and create an object of that class. What would an example be?

like image 856
user29772 Avatar asked Nov 14 '09 23:11

user29772


People also ask

Can I use classes in Arduino?

On Arduino you can use classes, but there are a few restrictions: No new and delete keywords. No exceptions. No libstdc++, hence no standard functions, templates or classes.

Can you use C++ classes in Arduino?

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!

Can I use OOP in Arduino?

Put a little OOP in your loop.The Arduino Language is a variant of C++ which supports Object Oriented Programming. Using the OOP features of the language we can gather together all of the state variables and functionality for a blinking LED into a C++ class. This isn't very difficult to do.


2 Answers

On Arduino 1.0, this compiles just fine:

class A {   public:    int x;    virtual void f() { x=1; } };  class B : public A {   public:     int y;     virtual void f() { x=2; } };   A *a; B *b; const int TEST_PIN = 10;  void setup() {    a=new A();     b=new B();    pinMode(TEST_PIN,OUTPUT); }  void loop() {    a->f();    b->f();    digitalWrite(TEST_PIN,(a->x == b->x) ? HIGH : LOW); } 
like image 110
Warren MacEvoy Avatar answered Sep 17 '22 21:09

Warren MacEvoy


There is an excellent tutorial on how to create a library for the Arduino platform. A library is basically a class, so it should show you how its all done.

On Arduino you can use classes, but there are a few restrictions:

  • No new and delete keywords
  • No exceptions
  • No libstdc++, hence no standard functions, templates or classes

You also need to make new files for your classes, you can't just declare them in your main sketch. You also will need to close the Arduino IDE when recompiling a library. That is why I use Eclipse as my Arduino IDE.

like image 43
Johan Avatar answered Sep 17 '22 21:09

Johan