Go Down

Topic: How do I write a Class in Arduino Language (Read 8963 times) previous topic - next topic

toast3d

Hi there..

I normaly are programming in Processing. Just one week ago I started with the Arduino. My small question: How can I write a "Class" in Arduino? When I do it like in Processing. Its not working ..:-(

bye
Daniel

mellis

You need to use C++ syntax, not Java like in Processing.  Take a look at the source code for the libraries in hardware/libraries - they have some examples.  Or see the tutorial on writing a library: http://www.arduino.cc/en/Hacking/LibraryTutorial

toast3d

Quote
You need to use C++ syntax, not Java like in Processing.  Take a look at the source code for the libraries in hardware/libraries - they have some examples.  Or see the tutorial on writing a library: http://www.arduino.cc/en/Hacking/LibraryTutorial


Sí Sí, thats what I supposed that I have to write it in C++ ;-) ...but I don't know how! -) But thanx a lot, so I will take a look at the "how to write a library" tutorial:-)

...is a Library in C++ the same like a Class in Java?

mem

#3
Apr 27, 2008, 12:00 pm Last Edit: Apr 27, 2008, 12:11 pm by mem Reason: 1
Quote

...is a Library in C++ the same like a Class in Java?


A library in the Arduino environment is typically written as a class but it does not need to be one. It just happens that the Arduino documentation on writing a class happens to be in a library tutorial.

A C++ class is similar but not exactly the same as a java class.  I posted an example of a simple java class ported to the Arduino here: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1207661024



MysteriousAges

Here's an example of a class:

Code: [Select]
class Button {
private:
 byte down_at;
 byte down;
 
public:
 Button();
 byte downFor();
 void resetDown();
 bool isDown();
 void turnOn();
 void turnOff();
};

Button::Button()
{
 this->down_at = 0;
 this->down = 0;
}

// Find the number of beats the button has been down for. Function can compute max. 8 sec down before rolling over.
byte Button::downFor()
{
 byte time;
 if (this->down_at > sc_beat)
 {
  time = (sc_beat + 256) - this->down_at;
 }
 else
 {
   time = sc_beat - this->down_at;
 }
 return time;
}

bool Button::isDown()
{
 return (bool)this->down;
}

void Button::resetDown()
{
 this->down_at = sc_beat;
 this->down = 1;
}
 
void Button::turnOn()
{
 if (!this->down)
 {
   this->down_at = sc_beat;
   this->down = 1;
 }
 return;
}

void Button::turnOff()
{
 this->down = 0;
 return;
}

Go Up