Structuring Arduino code
Posted on April 23rd, 2008 in programming |
One of the most important things in programming is writing understandable and readable code. Despite the fact that usually when you deal with electronics you have to write the code in very low level language, Arduino syntax is very close to such high level programming languages as C and PHP. If you know any of these languages, I bet there will be no problems for you.
The basic way of structuring your Arduino code is writing a normal procedural code. If we recall the example arduino code from the previous post, it was something like this:
if (condition){
digitalWrite(ledPin, HIGH);
delay(300);
digitalWrite(ledPin, LOW);
delay(300);
digitalWrite(ledPin, HIGH);
delay(300);
digitalWrite(ledPin, LOW);
delay(300);
}else{
digitalWrite(ledPin, HIGH);
delay(300);
digitalWrite(ledPin, LOW);
delay(300);
}
There is no problem with the code unless you want to give it to other people or be satisfied with the job you have done. The trick is that you can easily replace the identical parts with functions. Normally you can replace the 4 lines with just one function call:
if (condition){
blinkLed(300);
blinkLed(300);
}else{
blinkLed(300);
}
or even better
if (condition){
blinkLed(2, 300);
}else{
blinkLed(1, 300);
}
And the definition of the function:
void function blinkLed(times, lengthms){
for (int i = 0; i < times, i++){
digitalWrite(ledPin, HIGH);
delay(lengthms);
digitalWrite(ledPin, LOW);
delay(lengthms);
}
}
The idea is simple - you choose the time in milliseconds the led will be on and the number of times the blink operation should be done. That’s it. Now if we include this code in the previous example, the code looks cleaner as well as is readable easier:
int ledPin = 13;
int usbnumber = 0;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
usbnumber = Serial.read();
}
if (usbnumber > 0) {
if (usbnumber % 2 == 0){
blinkLed(1,300);
}else{
blinkLed(2,300);
}
usbnumber = 0;
}
}
void function blinkLed(times, lengthms){
for (int i = 0; i < times, i++){
digitalWrite(ledPin, HIGH);
delay(lengthms);
digitalWrite(ledPin, LOW);
delay(lengthms);
}
}
I don’t think it’s worth to rewrite the arduino website here, so go on and check out the function declaration manual.