Hardware Reference
In-Depth Information
Boolean TrafficLight::begin(void)
{
// Set pins as outputs
pinMode(_redpin, OUTPUT);
pinMode(_yellowpin, OUTPUT);
pinMode(_greenpin, OUTPUT);
// Set Yellow and Green off
digitalWrite(_yellowpin, LOW);
digitalWrite(_greenpin, LOW);
// Set Red on
digitalWrite(_redpin, HIGH);
return true;
}
The begin() function sets the trafi c light pins as outputs, and sets the yellow
and green lights to off. As a security, these trafi c lights will start with the red
light on, halting trafi c, adding a level of security before deciding which direc-
tion should be green. Next, you need to create functions to turn on individual
lights. When activating the green light, both the red and yellow light are to be
turned off. The greenLight() function might look like this:
void TrafficLight::greenLight(void)
{
// Set Red and Yellow off
digitalWrite(_redpin, LOW);
digitalWrite(_yellowpin, LOW);
// Set Green on
digitalWrite(_greenpin, HIGH);
}
Adding Comments
Comments are a critical part of any code and are unfortunately often omitted.
They serve several purposes and are particularly useful in libraries.
Most comments are used inside code to explain the function of a portion of
code. Of course you know what the code does; you have spent an hour writing it,
and even more debugging it, and it has become perfect: elegant and functional.
Would co-workers understand what you have done? They might have come
up with another way and may be confused by your code if it isn't explained a
little, no matter how elegant it is. Also, would you read your code 1 year from
now? You might have done dozens of different projects, and your coding style
 
Search WWH ::




Custom Search