Monday, October 12, 2015

Intermediate Arduino Programming 101: Rename Hardware Serial Port

Intermediate Programming 101: Rename Hardware Serial Port

Why would we want to rename a hardware device - it makes the code easier to follow and edit.
It also helps when there are more than one hardware serial device, like on the Mega
code like this:

void setup() {
Serial.begin(9600); //debug
Serial1.begin(4800); //gps
Serial2.begin(9600); //compass
}

Turns into this:
#define Debug Serial
#define GPS Serial1
#define Compass Serial2

void setup() {
Debug.begin(9600);
GPS.begin(4800);
Compass.begin(9600);
}

void loop() {
Debug.println(“This goes to Serial Console.”);
GPS.println(“Hi GPS…..GPS Doesn’t understand this”);
Compass.println(“Some stuff that compass doesn’t like”);
}



In this example we see something called #define, we all have seen this, may have even used it, or copied it from someone else's sketch, most don’t question what it is or what it does.
So - Here is what it is, and what it does:

#define is a useful C component that allows the programmer to give a name to a constant value before the program is compiled. Defined constants in arduino don't take up any program memory space on the chip. The compiler will replace references to these constants with the defined value at compile time.

You can #define your own constant as well example a LED pin.

#define RedLed 3

This makes things a little easier on the programmer, he/she doesn’t have to remember that the RedLed is connected to Pin 3 - or even better, you just have to change one thing should the RedLed move to Pin 4.

To the Arduino - (after the sketch is compiled and running on it) - it replaces all of the RedLed references to 3.

So in our Serial example above - at the time the sketch is compiled, the compiler sees this:

void setup() {
Serial.begin(9600);
Serial1.begin(4800);
Serial2.begin(9600);
}

void loop() {
Serial.println(“This goes to Serial Console.”);
Serial1.println(“Hi GPS…..GPS Doesn’t understand this”);
Serial2.println(“Some stuff that compass doesn’t like”);
}


So this sounds great right? Now for the warning,

There can be some unwanted side effects from using this method.
if for example, a constant name that had been #defined is included in some other constant or variable name. In that case the text would be replaced by the #defined number (or text)
In general Arduino prefers using the const keyword (https://www.arduino.cc/en/Reference/Const) for defining constants.


So that is it in a nut shell. Quick and Easy way to rename hardware components.

No comments:

Post a Comment