Using classes with the Arduino

user29772 picture user29772 · Nov 15, 2009 · Viewed 138.1k times · Source

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?

Answer

Warren MacEvoy picture Warren MacEvoy · Oct 6, 2012

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);
}