Getting Started with Programming – part 1: Skimming the Surface

If you’ve never touched it before, getting started with programming can be a daunting task. Luckily, there are countless of good resources around the interwebs on how to get started. Despite this, we’re going to write our own little series on how to get the grips of the programming basics.

Our main focus will be heavier on the hardware and embedded systems side of things and not on the typical desktop software or mobile applications side. But since this is a series for beginners all the topics in this series will be applicable practically everywhere in the common world of programming.

We’ll try to write this series independent of programming language, but include example code in a couple of languages as well as pseudocode.

Pseudocode is code written for humans and not machines […]

Languages

You should look at programming languages like toolboxes.

There are probably hundreds of different programming languages out there, some more obscure than others. You should look at programming languages like toolboxes. You don’t take your plumbing toolbox with you to fix your hifi system and you don’t bring your metalwork toolbox to make a wooden chair. Every language has several properties which make them more suited for some tasks than others. Some are however definitely more versatile than others and often it’s only a matter of subjective choice between what languages to use for a specific application.

Here’s a list of the ten most “popular” programming languages in 2015.

  • At the top we find Java, a popular language for desktop-, web- and mobile based applications.
  • Then you have C which is more directed towards low level areas such as microcontrollers in embedded systems and other hardware, but still versatile.
  • C++ on third place is sort of a powerful expansion of C with more features. This is the language Arduino has based its language upon. Every feature and syntax in C is in practice also in C++ (link for the nerd). When writing C++ code to an Arduino it will look quite different than when writing for a Windows program, for instance. The functions available differ greatly, but much of the basic syntax is the same.
  • On fourth place we find Python which really stands out from the others in the top five. It’s a high-level language which is made to do complex operations within few lines of code, while not requiring compilation (translation from human-written code to code that the computer understands using a compiler) of the code before running (as opposed to the others). You can also run the exact same code on many different platforms.
  • The last example we’re going to mention is C# on fifth place which is a modern alternative to C++ developed by Microsoft aimed towards more high-level applications.

For this series we’ll use the Arduino version of C++ and Python 2 (not 3) as example languages. Arduino since it’s so popular and Python since it’s applicable on most platforms and since it’s easy to test your code without compilation and a complicated setup.

You can look at syntax in a programming language as the grammar in a regular language.

We briefly mentioned the word syntax. You can look at syntax in a programming language as the grammar in a regular language. Every programming language is a proper grammar nazi, so be sure to keep your syntax correct at all times.

Again remember that the Arduino language needs to compile before executing as opposed to Python. It’s easy to think that this is a very nice thing for Python, but when compiling code you often root out simple syntax errors from the whole code. Python only get syntax errors when it encounters the error in the code while the script is running, which can be two years down the line after delivery to the client, so choose your languages wisely!

The Basics

Control Flow

A typical computer can only do one thing at a time […]

An important concept to understand is control flow. It’s not as complicated as it might seem.

A typical computer can only do one thing at a time, so the order you do things in is crucial. The control flow is basically how the program traverses the code. This can be visualized in so called flowcharts.

Flowcharts

Drawing flowcharts for programs you’re going to write is a really nice (and highly recommended!) way to get a proper overview of your program BEFORE writing the code. Here are a few less serious examples of flowcharts, not necessarily aimed for computer programs.

source: http://mentalfloss.com
source: http://mentalfloss.com
source: xkcd.com
source: xkcd.com

Let’s look at a more useful and relevant, yet a bit silly, example of flow control. Let’s say you have a very simple temperature control system and want to keep the temperature in a room within a certain range. You have a motorized window opener, a heater (without a thermostat) and a temperature sensor.

A useful flowchart for a simple embedded system
A useful flowchart for a simple embedded system

As you can see in this example (as opposed to the less serious ones above), the system doesn’t have an end/termination condition, which means that the program won’t shut itself down or end in some way. This is often desirable in embedded systems like this: you just want it to always run. After making this chart (it’s sufficient to scribble it down on a napkin) it’s super easy to write the code for the system since all the logic already is in place.

Common “Statements”

The most common building blocks for guiding the program through the code so that it does what it’s supposed to can be divided into Conditional statements and Loops.

[Conditional statements] basically works such that you check if a condition is true or not […]

Conditional statements are in all of the flowcharts above represented by a diamond. The most common conditional statement is the If-then-(else) statement or just the “if statement”. It basically works such that you check if a condition is true or not (temperature bigger than 25, LED turned off, some variable equal or unequal to some number, etc…) and then access certain parts of the code based on the “answer” (yes/no, true/false).

[…] loops might sound a bit cryptic at first, but they are a completely necessary programming tool.

Loops are parts of a code which in some matter will be repeated a certain amount of times (For loops) or until a condition changes (While loops). This doesn’t necessarily mean that the program is doing the exact same thing over and over again, but a certain chunk of the code will repeat while for example some variables change on each pass. These loops might sound a bit cryptic at first, but they are a completely necessary programming tool. For instance, in our temperature control system the whole main chunk of the code (all the logic that is represented by the flowchart) would have to be within a single while loop to be able to repeat an indefinite amount of times.

We will later go into more details around these so called statements.

Variables

You practically always need to use variables.

In programs it is completely necessary to be able to store values. These values can often easily be stored in something called variables and can be numbers (either integers or decimal numbers), single letters (always called characters), text (a string of characters) or just boolean variables (true or false). The availability of these different variable types differ from language to language. C, for instance, doesn’t have strings (the text type variable), but gets around that by being able to create an array of characters, which we will talk about in the next section.

You practically always need to use variables. If you read a sensor, you can store the value in a variable. If someone gives an input with a keyboard to the program, you can store the string in a variable. Variables can also be changed and manipulated in many ways, for instance with mathematical operators (add, multiply, subtract, divide and so on), both using other variables and constant numbers.

Let’s do a quick and easy example of mathematical variable manipulation. We’ll use three variables (A, B and C)  where two of them (A and B) initially are integers and the third (C) is the average of A and B. Then we will multiply C by 3 and update C with that value. Lastly we’ll divide C by 4 and update A with that value.

Pseudocode

Pseudocode is code written for humans and not machines and the point of it (at least in this series) is to write a piece of code regardless of programming language. There are “correct” pseudocode syntaxes, but we’ll just wing it and go for something that’s easy to understand.


variable A is 2
variable B is 6
variable C is (A + B) / 2
C is C times 3
A is C / 4

When updating the values of the variables, it’s completely overwritten, forgetting the last value it had.

Arduino

Now let’s write valid code for the above operations for the Arduino.


int A = 2;
int B = 6;
int C = (A + B) / 2;
C = C * 3;
A = C / 4;

These C-related languages doesn’t give a s**t if you format everything nice and tidy or not.

There are a couple of things to note here.

  • int is the data type of the variables. In C, C++ and Arduino int means integer, i.e. no decimals. Once you’ve declared or initialized a variable with a specific datatype (you need to specify a data type!), like in lines 1, 2 and 3, don’t use the data type when referring to that variable later in the code (lines 4 and 5). Since the program always start at the top of the code, moving line 5 to the top wouldn’t work for two seperate reasons: the variable A wouldn’t have been declared with a type yet, and it wouldn’t know what C is.
  • Notice the semicolons at the end of each line. These C-related languages doesn’t give a s**t if you format everything nice and tidy or not. If you want, you can write everything on one single line: the semicolons are what matter and they need to be there to mark the end of a line.

Python


A = 2
B = 6
C = (A + B) / 2
C = C * 3
A = C / 4

Python does take formatting into account

Notice that the semicolons and the ints are gone! Python looks at the values set for each variable and assigns the data type based on the value to the variable: 1 becomes an integer, 1.0 becomes a float (decimal number) and “biscuits” becomes a string. Also, Python does take formatting into account (as opposed to the language(s) above). So a line break in the text editor is taken into account when running the code, as well as indents, which we will see later.

Arrays

An array (not always called that, but we’ll call them that here) is basically a list of variables of a certain type, for instance a list of numbers or a list of characters. These arrays can be in how many dimensions you like. One dimension forms a typical list, two dimensions form a table like in a spreadsheet. For loops are often used to traverse arrays. We will later go into detail in how to make and use these.

Commenting

When writing code, you often tend to lose overview when the number of lines increase. For this reason (amongst several others), commenting is a very handy tool. Comments are letters, symbols, words and sentences whis the compiler ignores. You can look at comments as notes to yourself or others who’re going to read the code, and these can be crucial for the readability of your code. Here’s how you comment in C++/Arduino and Python:

Arduino
//this is how
//you comment single lines

int my_variable = 123; //you can also comment like this

/* 
this is how you comment
several lines at once
*/
Python
# this is how
# you comment single lines

my_variable = 123 # you can also comment like this

""" 
this is how you comment
several lines at once
"""

The blue lines in both of those code snippets are all comments and will be ignored during compilation (Arduino) and run time (Python).

Necessary Preperations

[…] programming works great as learning by doing.

This chapter is for setting up the enviroment for writing and running example code. We recommend that you try things out yourself since programming works great as learning by doing.

Arduino

Go to Arduino’s Getting Started page to get started with download and installation. Arduino comes with an own editor (IDE) where you can write and compile your code and upload it to the board. Remember that the code you write is actually running on the Arduino and not locally on your PC or Mac. You’ll need an actual Arduino and a USB cable as well of course. If you’re unsure of what to choose we recommend the Arduino Uno.

Python

Go to this page for instructions on how to download and install Python on your machine. You can choose between writing the code in a general purpose text editor (such as Notepad++) or downloading one of many Python IDEs.

The simplest would be to use a text editor, save the code as a .py file in an easily accessible folder, open the command line (in Windows press WindowsKey+R and write cmd and press OK; in Mac find the Terminal app) and write python mypythonfile.py (if your python file made in the text editor is called mypythonfile.py) and press enter while being in the correct folder to run your python script.

Basic Coding Example: “Hello, World!”

The typical first program someone writes when trying a new language is printing “Hello, World!” to whichever console or display is available.

Pseudocode

print "Hello, World!"

Arduino
void setup() {
    Serial.begin(9600);
    Serial.print("Hello World");
}

void loop() {
}

When you start the Arduino IDE, the void setup() and void loop() functions (we’ll talk about functions later) are there already. You just need to fill in code where it’s supposed to go. The code that’s only supposed to run once goes inside the setup function and the code that will run over and over again goes inside the loop function.The indentation is there for readability only (unlike Python). The curly brackets { } are there to define what’s inside the functions and are required in this language (for more than one line of code). Sometimes you want to write code outside those functions as well, but we’ll get back to that later.

To gain access to the terminal where you’ll se what you’re printing over serial, press ctrl+shift+M. We have coded this in the setup function, so it will only print it once. Remember to set your baud rate in the terminal to 9600 (the same as in the code).

For the extra curious: to illustrate some of the differences between standard C++ and the Arduino language, this is how the code would look in C++ if you were to to print Hello, World! to the terminal:

#include <iostream>

using namespace std;

int main()
{
  cout << "Hello, world!";
}

As you can see, this is quite different from the Arduino code, but serves roughly the same purpose (very roughly).

Python
print "Hello, World!"

Here’s a neat example of how simple Python code can be: identical to the pseudocode!

Summary

There are tons of different languages and you have to choose what language is best suited for the task and what you’re familiar with.

We will use the Arduino-version of C++ and Python as example languages throughout this series as well as pseudocode.

It’s important to understand that a typical computer only does one thing at a time. The way the program flows through the code is called control flow. Sketch out a flowchart on a piece of paper before coding to save a lot of time.

You can get a lot done with variables, if-then-(else) statements and loops, arrays and a few functions. These are all topics that we’ll visit more in detail later.

Upcoming Topics

We’ve just skimmed the surface of basic programming. Later we need to look at the statements we mentioned (conditional and loops), functions, the difference between local and global variables, strings, type casting, arrays/lists, defines and maybe structs and objects as well as other oddities. So there’s a lot to look forward to! 🙂

Continue to part 2 where we talk about conditional statements.

Related Posts