Arduino IDE 0012 Alpha questions (newbie)

Welcome to the world of Arduino and C.

You may find that the C language is a little rough if you are used to the elegance of Delphi, but it's not difficult picking up the essentials you need to make the arduino sing.

There is nothing wrong with the C code in your sketch, but your outputs start at pin 1 and this is used for the serial port on Arduino ports with USB or RS-232. So pin 2 may be a better place to start.

There are some C constructs that you may find useful and I have modified your sketch to illustrate these. Feel free to use or ignore any of these suggestions, they are stylistic and down to personal preference.

  • You can use the C preprocessor to define constants (conventionally written in upper case in C ) to make code more legible

  • LOW and HIGH are Boolean values (even though C does not have a strict Boolean type like Pascal) so you can use Boolean expressions instead of doing an if/than test

  • you can use the shift left operator << to handle the mask. Shifting left 1 (mask = mask << 1) is exactly the same to the compiler as mask = mask2 but using the shift operator make your intentions clearer. Also, in C mask <<=1 is the same as mask = mask <<1. This works for all operators, for example mask=2 ;

#define START_PIN  2  // defines the start pin, 
#define END_PIN 9

void setup()                    // run once, when the sketch starts
{
  for (int i=START_PIN; i <= END_PIN; i++){
  pinMode(i, OUTPUT);      // sets the digital pin as output
  digitalWrite(i,LOW);
  }
}

void loop()                     // run over and over again
{
  for (int i=0; i<=255; i++){
    int mask=1;
    for (int bit = START_PIN; bit <= END_PIN; bit++){  
      digitalWrite(bit, i & mask);  // HIGH if mask & 1 else LOW
      mask = mask << 1; // shift mask left (could also be: mask <<= 1);
    }
    delay(200);
  }
}

Some differences between C and Delphi/Pascal that can catch you out are:

  • Semicolons are part of the syntax, leaving them out can generate errors but adding one just after a conditional test can create subtle bugs
  • Typing in C is weak, the compiler wont catch many errors that it can in Delphi
  • Array syntax is different in C and the C string handling is extremely primitive!
  • Pascal records are structures in C

Have fun!