Hardware Reference
In-Depth Information
1 class TrafficLight
2 {
3 private:
4 int _redpin, _yellowpin, _greenpin;
5
6 public:
7 TrafficLight(int redpin, int yellowpin, int greenpin);
8 void begin();
9 void red();
10 void yellow();
11 void green();
12 };
First, the class
TrafficLight
is dei ned. This is the object that will be cre-
ated in your sketch. Next, it has two parts: one called
public
and one called
private
. The
public
section is where you will place functions and variables
that will be visible to the sketch. This includes functions for controlling the
state of the lights that you (or someone else using your library) will call in the
main sketch. The
private
section contains functions and variables that are
not visible to the sketch, only to the object. You can see how this works in a
few paragraphs.
On line 7, there is an interesting function. It is called
TrafficLight
, the same
name as the class. It takes three parameters, does not return any data, and isn't
even declared as
void
. This is known as the
constructor
, which is a function
that is automatically called when the object is created and is even called before
setup()
. The constructor is vitally important because it initializes any variables
that need to be set up before the sketch has a chance to execute any functions.
Typically, constructors take parameters, in this case the pins that will be used.
There is another important requirement for header i les. When a header
i le is imported, the i le is parsed, and the compiler knows what functions are
available. If the same i le is imported again, it can lead to confusing results, and
compilers will complain. To make sure this does not happen, it is common to
wrap up the header i le in a construct:
#ifndef TrafficLight_h
#define TrafficLight_h
// Include statements and code go here
#endif
This construct prevents problems if somebody includes the library twice.
In the sketch, the
TrafficLight
object would be created like this:
const int redNorthPin = 2;
const int yellowNorthPin = 3;
Search WWH ::
Custom Search