Hardware Reference
In-Depth Information
const int greenNorthPin = 4;
TrafficLight northLight = TrafficLight(redNorthPin, yellowNorthPin,
greenNorthPin);
When this object is created, the constructor is called with the three variables.
Now it is time to write the constructor. This function would be included in
TrafficLight.cpp :
TrafficLight::TrafficLight(int redpin, int yellowpin, int greenpin)
{
_redpin = redpin;
_yellowpin = yellowpin;
_greenpin = greenpin;
}
The function is extremely simple, but it does differ from functions
that have been previously written in this topic. First, the function name:
TrafficLight::TrafficLight . The i rst part, TrafficLight:: , is the name of
the class that the function will belong to. The second part is the function name.
Because this is a constructor, it must have the exact same name as the class. It
takes three int variables. Inside the function, the parameters it was given are
stored in three variables: _red , _yellow , and _green . Where do they come from?
They were dei ned in the header i le on line 4. Because they are in the private
section, they cannot be called from the sketch but are used inside this particular
class object. Let the user have access to the required functions, and keep the
rest hidden away. Imagine that you have two trafi c lights, a northbound light
and a southbound light. They are created like this:
TrafficLight northLight = TrafficLight(1, 2, 3);
TrafficLight southLight = TrafficLight(9, 8, 7);
Both have been created with different variables. When these objects were
created, each called the constructor independently. Their private variables are also
different: northLight 's _red variable contains the value 1, but southLight 's _red
contains the value 9. You can create many objects with the same functionality but
with different variables. This makes it possible to turn the northbound light red,
stopping all trafi c, while turning the southbound light green, allowing trafi c
to go straight, or to turn at a rather difi cult junction, without any other trafi c.
On line 8 of the header i le, there is another function, begin() . You have seen
functions with the same name throughout this topic, which are used when a
device is ready to be used. The constructor set up only the variables; it did not
set any outputs, or even declare any pins as output. Typically, this is done in a
begin() function. The sketch might need those pins for something else before
using a trafi c light, so it is often good practice to wait until the begin() func-
tion is called. A begin() function might look like this:
Search WWH ::




Custom Search