12) Preprocessor Directives

Preprocessor Directives are code for the compiler. This code will not and cannot be used by the robot. Preprocessor Directives are lines that start with a hash, "#". There is a big list of Hash commands, in which include:
  • #include
  • #define
  • #pragma
  • #ifdef
  • #ifndef
  • #if
  • #elif
  • #else
  • #endif
  • #import
  • #using
  • #line
  • #error
  • #undef
And most of those you won't need for your robot! But the two I would like to go over are "#include" and "#define".

#include:
This action is a really cool option to C/C++. This code tells the compiler to get existing code from a known folder. This both hides the extra code (no copy and pasting in code), as well as automatically updating the code in all projects if the code is ever updated. Whenever you need to use a servo or a stepper motor, you can use the code the library for that piece! To find all the libraries that you can use, go to http://arduino.cc/en/Reference/Libraries. I will only be going over Servo.h, but that is in another tutorial.
#define:
This action replaces every instance with another instance.
#define PIN_motor 5
This command changes every instance of PIN_motor to 5.

Some examples like to define their pins as variables. But I disagree. You should only use a variable if the number changes, or if it is one of the arguments of a function. Instead I would define all my pins using "#define", like so:
#define PIN_motorLeft_Forward 5
#define PIN_motorLeft_Reverse 6
#define PIN_motorRight_Forward 9
#define PIN_motorRight_Reverse 10

void setup()
{
}

void loop()
{
  setMotorLeft(75);
  setMotorRight(-100);
  delay(3000);
  setMotorLeft(-100);
  setMotorRight(75);
  delay(3000);
}

void setMotorLeft(int speed)
{
  if (speed>=0)
  {
    analogWrite(PIN_motorLeft_Forward,speed*2.55);
    digitalWrite(PIN_motorLeft_Reverse,LOW);
  }
  else
  {
    analogWrite(PIN_motorLeft_Reverse,-speed*2.55);
    digitalWrite(PIN_motorLeft_Forward,LOW);
  }
}

void setMotorRight(int speed)
{
  if (speed>=0)
  {
    analogWrite(PIN_motorRight_Forward,speed*2.55);
    digitalWrite(PIN_motorRight_Reverse,LOW);
  }
  else
  {
    analogWrite(PIN_motorRight_Reverse,-speed*2.55);
    digitalWrite(PIN_motorRight_Forward,LOW);
  }
}


As another habit, I would like everyone to establish a standard to define all their pins. I would highly recommend using "PIN_" to declare all ports.
Comments