5 Tips To Improve Your Arduino Coding Skills

Code.jpg

I have been programming on and off in different languages throughout my 30 + year career for different reasons. One thing I learned quickly that all programming languages have one thing in common. You can write a fully functional program that 24hr from completion nobody can understand how it works; even the programmer her/himself is completely confused how it ever could work.

The first step in learning a new programming language is how to write legible code (in my opinion that is). It is tough to do when you start learning, but if you follow the 5 tips you will see the difference in how quickly you will improve you skills, and be able to reuse your code even months after you are done with the project.

1. Use descriptive Variable names

I see this so often;  int x=100;, or String y=”hello molly”;. It is completely legal, and correct to do so, but the names of these variables don’t say anything about what they do. Even if the x, and y in this example have something to do with plotting data on a x/y axis the names are too ambiguous.

Always give your variables names that make sense, e.g.  int x_Axis=100;. If you declare a variable for a digital pin that is going to be used with a button that turns an LED on, use button_led_on_off_Pin. This name has meaning. It tells you it has something to do with a button that is turning an led on and off.

In my opinion the only place where it is OK to use single character variables are in things like a for() loop initialization variable, or something similar.

2. Indent your code appropriately

Indent your code appropriately! If you have a nested if statements that are not indented properly it becomes really hard to read your code. It will be even harder to debug if you have a logic error (your code syntax is correct, but the code doesn’t do what you expected it to do) take this code example:

void loop() {
if(hedgehog==cat){
if(cat==likehedgehog){
  //hedgehog and cat are friends
}else if(hedgehog!=cat){
  //hedgehog and cat are friends
}else if(cat != hedgehog){
  //hedgehog and cat arn't friends
}
}else{
  //hedgehog and cat are not in the same room
}
}

Now see the next code example using indentation:

void loop() {
  if(hedgehog==cat){
    if(cat==likehedgehog){
      //hedgehog and cat are friends
    }else if(hedgehog!=cat){
      //hedgehog and cat are friends
    }else if(cat != hedgehog){
      //hedgehog and cat arn't friends
    }
  }else{
    //hedgehog and cat are not in the same room
  }
}

Notice how much easier it is to read your code. Your eye can see how these if() statements are nested and it makes it a lot easier to find your logic error. Sometimes I forget to add a closing bracket. You complete your code and get “expected '}' before 'else'” error message when compiling. In the indented code example it would only take seconds to figure out what bracket was missed, good luck to find the error in the non-indented code.

3. Use Commends please

Commends are part of the documentation process (but are not considered documentation) All programming languages allow you to give comments. In my opinion giving a short explanation what a variable is used for (at the instance of declaration) makes a lot of sense, and gives the person trying to understand your code (could be yourself three months after you finished) an inside what this variable is used for.

int cat=0; //If the cat is in the room the value is 1, otherwise the value is 0

If you have a complex nested if() statement or for() loop you could do something like this.

void loop() {
  int cat=0;//If the cat is in the room the value is 1, otherwise the value is 0
  int hedgehog=0;//If hedgehow is in the room value is 1 otherwise the value is 0
  int likehedgehog=0;//If the cat likes the hedgehog value is 1, otherwise value is 0
  int likecat;//If hedgehog likes the cat the value is 1, otherwise value is 0
    
    /**
     * This nested if() block is to check if the hedgehog and the cat are in the same room.
     * If they are in the same room we check if they like eachother 
     * If the cat likes the hedgehog everything is fine, if the cat doesn't likethe hedgehog
     * they need to be seperated
     */
    if(hedgehog==cat){
        if(cat==likehedgehog){
            //hedgehog and cat are friends
        }else if(hedgehog!=likecat){
            //hedgehog and cat are friends
        }else if(cat!=likehedgehog){
            //hedgehog and cat arn't friends
        }
    }else{
      //hedgehog and cat are not in the same room
    }
}

Notice that the extended description helps the person reading your code understand the function of this block of code. I also put an extended description at the top of my sketches explaining what the function of this code is, my name and sometimes my contact info, the date I finished, and the version of this current code.

/**
 * Author:Ab Kurk akurk@thearduinomakerman.info
 * Date:04/Dec/2017
 * Version 1.0.0
 * Description
 * This sketch is to be used to track the location of my cat and hedgehog.
 * The purpose is to make sure that today my cat likes my hedgehog.
 * 
 */

If I later on go back and I make changes I update the version, and give a description what I altered, what date, and who altered it at the bottom of the description block.

4. Use functions() to organize  and reuse your code

Functions might be considered a intermediate level , but even as a beginner it makes sense to try to do this. If you have big blocks of code that serve a specific purpose it makes sense to put it in a separate function. It makes your code more readable, and might also reduce the amount of code you write because it is easier to reuse the same code in a different part of your program.

As an example here is a piece of code from a previous tutorial I did about reading data out of memory. First without the use of a function;

void loop() {
  // put your main code here, to run repeatedly:
  String ssid="";
  String password="";
  /**
   * Reading the ssid out of memory using the eeprom library
   * The ssid starts at memory position 0 and is 30 characters long
   */
  
  for (int n = 0; n < 30; ++n)
    {
     if(char(EEPROM.read(n))!=';'){//looking for end of data character ';'
        if(isWhitespace(char(EEPROM.read(n)))){//Remove whytespaces e.g. a space 
          //do nothing
        }else ssid += String(char(EEPROM.read(n)));
      
     }else n=31;
    }

  /**
   * Reading the password out of memory using the eeprom library
   * The ssid starts at memory position 100 and is 30 characters long
   */
  
  for (int n = 100; n < 130; ++n)
    {
     if(char(EEPROM.read(n))!=';'){//looking for end of data character ';'
        if(isWhitespace(char(EEPROM.read(n)))){//Remove whytespaces e.g. a space 
          //do nothing
        }else ssid += String(char(EEPROM.read(n)));
      
     }else n=131;
    }
}

You see that we have two blocks of code doing the exact same thing. Here is an example of the same code but using a function;

void loop() {
  // put your main code here, to run repeatedly:
  String ssid="";
  String password="";
/**
   * Reading a string out of memory using the eeprom library
   * The read_string(length of data int,position in memory int) is a function
   * you call to read data out of memory. You give it the start position
   * in memory and the length and it returns a string containing the data
   */
  ssid=read_string(0,30);//read ssid out of memory
  password=read_string(100,30);//read password out of memory

/**
 * Reads a string out of memory, l is the length of the data to be read out of memory,
 * p is the position in the memory where to start reading 
 */
String read_string(int l, int p){
  String temp;
  for (int n = p; n < l+p; ++n)
    {
     if(char(EEPROM.read(n))!=';'){
        if(isWhitespace(char(EEPROM.read(n)))){
          //do nothing
        }else temp += String(char(EEPROM.read(n)));
      
     }else n=l+p;
     
    }
  return temp;
}

You can see that I reused code by creating a function. This makes it easier to read, and uses less memory on your controller board. If you get proficient at using functions you will save time  and create more user friendly code that you can reuse in your next project

5. Document, document, document

The documentation of your project is probably the hardest, and the most boring thing about your project. To me it always felt like a annoying  task that wasn't really needed. To clients and employers it is often seen as a waste of time and money. The reality is that it always will save time and money on the back end of a project.

 In my documentation I always have a software section and a hardware section of my arduino project.

The software:

  • The libraries I used, the versions, and where I got them from if I downloaded them.
  • All the functions I created and a description of their function and what line you can find them.
  • Any methods and their children
  • A full explanation of what the sketch does, and how to use it.

The hardware section:

  • I put in a schematic of how to connect it to my development board. I often use the fritzing program for this. It is easy to use and free.
  •  Each breakout boards and sensors that is used in the project, what pins I connect them to. I also note down what software libraries are needed for this hardware.
  • If it is an exotic sensor or breakout board I also note down where I bought it

In Closing

If you adopt all or some of  these tips, you will become a better programmer/maker. It also means that if 6 months down the road you do the same type of project you can look back at your previously completed projects and reuse your code and ideas and not constantly have to reinvent the wheel.

I know out of experience that it looks a lot easier and spent less time not doing all this and just write code without formatting and documentation, but you would be wrong.  I often wasted so much time trying to understand why I did something a certain way, or was trying to figure out why a variable changed values just because I reused it in the wrong way.

If you like this post and would like to see more of the same type, please subscribe to my newsletter using the form below or like my Facebook page. This way you get notified when a new post is available.  If you have questions or suggestions please email me or leave it in the comments below. Have a great day and see you next time

Subscribe to our mailing list

* indicates required
Email Format