Getting Started with Arduino – Writing Codewith David

Summary

This lesson will help you understand the basics that will allow anyone to begin programming the Arduino to perform simple tasks, such as read input values, evaluate data, and make decisions about which section of the code to execute next.

Objectives

When you are done with this lesson you will

Know how to setup and use the Arduino IDE (Integrated Development Environment)

Know the main components of a program (sketch)

Be able to use basic commands to create functions for the computer to execute

What is the Arduino Programming Language?

A programming language is just like any other language in the sense that the developer gave names to different functions making them easier to remember and use. Each word or phrase represents a set of instructions that are built into the platform, allowing anyone to get stared with minimal training. The Arduino IDE (Integrated Development Environment) is a simplified version of two common programming language C / C++ (pronounced “C – Sharp”). Arduino is an open source platform.

What is Open Source?

Generally, open source refers to a computer program in which the source code is available to the general public for use or modification from its original design. Open-source code is meant to encourage collaboration, where programmers improve upon the source code and share the changes within the community. Code is released under the terms of a software license. Depending on the license terms, others may then download, modify, and publish their version (fork) back to the community.

Okay, so that basically means that someone wrote some code and, instead of keeping it a secret, shared it with the world on the condition that others who use it do things like give proper credit to the author and share their changes, modifications, and other improvements with everyone else. Some open source code may be used for commercial purposes while others are licensed for personal use only.

Loading the Arduino IDE onto your computer

In order to program the Arduino, you will need to download the Integrated Development Environment (IDE). This is the platform for writing the code that will run on your Arduino.

You can choose from the Arduino Web Editor, which will allow you to use a web browser to write your code, store it in the cloud, and upload it to your Arduino. This is a great option for Chromebook users or people who need to access their files from multiple computers.

Or you can download the Arduino IDE to your PC, Mac, or Linux machine. This is a good option if you have a slow internet connection or you work on your programs in places where you are unable to connect to the internet.

The steps are fairly straight-forward for either option. For this tutorial we will choose to download the Windows version.

1) Click on Windows Installer2) Click on Save File

3) Save to the location of your choice and the run the executable file (.exe)

4) Click Next through the prompts to allow the application to install.5) Once the program is open, go to Tools > Board and select the type of Arduino you want to program. An UNO R3 (Arduino-compatible) comes with each Creation Crate project.

Programming Basics

There are three main parts of an Arduino program, the
, the values, and the functions.

Values – Specific information (data) that the program may use to determine what to do as the program runs. Programmers assign a name and a value to a variable so it is easier to understand and can be used throughout the program to make decisions as to what the computer should do next based on its value at the time. These values may be constant (never changes) or variable (may change as the program is running).
Structure – Commands that make up the framework that a programmer will use when writing a program. The “IF” command is an example of basic programming structure. When an IF statement is encountered as the code is running, the computer will begin the process of comparing certain values and then deciding what to do next.
Functions – Sections of the program that are written to perform a specific task. Separating the program into discrete functions helps the programmer keep track of them separately, run them only when needed, and allows other programmers to more easily understand how it works.
Below is an analogy to something much more familiar to many of us, an automobile. This may help us to better understand these three parts and how they work together to perform complex functions, like keeping your engine running smoothly and efficiently.

Structure

We can compare the Structure of the program to the components of an engine. When we get into the car, we know it has a starter, a motor, a transmission, and a bunch of sensors. These are basic to the operation of the engine and their name and basic function does not change while we are driving the vehicle. Two examples of structural components are the Setup() and Loop() commands.
Every Arduino sketch starts with the Setup() command. This command will provide the computer with the basic information necessary to get started. It will only run one time because this information will not change during the execution of the program. For example we may tell it that we will be using a variable named “ambientLight” that will store the value from the sensor indicating whether it is light or dark. We are not going to change the name or type of this variable during the execution of the program.

This is a bit like starting a car’s engine. We send a signal to the starter which turns the crank and helps get the engine going. This only happens once during the operation of the vehicle. We will not need to start the car again until we stop the engine completely. We also won’t start calling the “engine” a “light bulb” and tell it to stop combusting fuel and instead to glow while we are driving down the road.

We use a Loop() to monitor conditions, evaluate results, and decide on the actions to take. Like the name implies, this is something that happens over and over again while the program is running.

Modern automobiles have a computer that is constantly evaluating information coming from the its many sensors that help it determine, among other things, the amount of fuel and air allowed to flow into the engine. Once the data coming from the sensors has been evaluated, the computer sends signals to the fuel injectors allowing them to pump fuel and to a flap that opens and closes to control flow of air. The more precise the mixture, the more efficiently the engine will run, so this is done over and over again, hundreds of times a minute while we are driving.

Values

When we write a program, we need to decide on what factors will change what the program does or when it does it. In order to do this we need to create a variable by assigning it a name and data type. Above we chose to create a value called “ambientLight.” We would also need to indicate that this variable is Boolean, which means that it will either be True or False, usually represented as 1 or 0. The value of a variable can be static (does not change) or dynamic (may change).
Constants – These are static values, settings, data types, etc. that do not change. Things that do not change in your engine would be its configuration and size.

The engine has 4 cylinders and each cylinder has a specific volume of space where combustion takes place, etc. These would be considered constants. Also, sensors like the thermostat will provide us with a temperature reading and not the velocity of the vehicle.

Variables – These are dynamic values and may fluctuate.

Values that may change during the operation of the vehicle would be the internal and external temperatures, amount of oxygen in the air, vehicle acceleration, etc.

Functions

Programs may be as simple as a few lines of code and perform a basic function. On the other hand, modern video games, for example, have millions of lines of code. Yes, MILLIONS! First of all, this is way too much for one person, or even a team of people, to manage. Second, we end up telling the computer to do the same thing so many times that it would not make sense to have to re-type the same code over and over again. Instead we write functions to do a specific job. These functions can then be executed whenever we need them. Some functions are part of the coding platform and are universal; others we write specifically for the application we are creating.

In our automobile we have a gas pedal that is connected to the throttle. Its sole purpose, or function, is to control the amount of fuel that we want to provide the engine and thus control its acceleration. We also have a coolant pump that help keep the engine operating at the correct temperature. These functions can do their job as needed and without getting in one another’s way.

Knowledge in Action

We will now evaluate a simple program that was written to turn a light on or off based on the position of a switch. If you are not yet familiar with the Arduino microcontroller’s hardware you can find a lesson on our website that will help you. Getting Started With Arduino
The Arduino has many “pins” that can be used to receive information (Inputs) or send information (Outputs). What the pins are actually used for is up to the programmer. The command pinMode() is part of the platform and can be used by the programmer to configure the pin. Instead of writing all of the lines of code that actually configure that pin, it has been given a name and can be used at any time.
If this pin was going to be used to read the information coming from a sensor, such as the one used to detect the light, we would write a function that checks and captures its value at a set interval. Another function used to send a signal to the LED to turn it on/off would also run at a set interval and execute a command based on the data it received.
Okay – here’s the no-jargon version of what we just learned:
The ambientLight function checks the sensor and if the sensor says it’s light, it will keep checking again and again until the sensor tells it its dark. When the sensor says it’s dark it will send signals to the LEDs turning them on and off to create different colors until it detects light again.
The code below will monitor the state of a button, whether it’s in the OFF (open) state or the ON (closed) state. When the button is ON then the Arduino will send a signal to the LED to turn it on.

GLOSSARY

Programming Language - A vocabulary and set of grammatical rules for instructing a computer to perform specific tasks. The term usually refers to high-level languages, such as BASIC, C, C++, COBOL, FORTRAN, Ada, and Pascal. These languages are developed to make programming easier by providing a set of commands that can perform different functions that would otherwise require writing many lines of code.
Code – A set of instructions to tell the computer what to do.
Statement – One complete instruction.
Sketch – A complete program used to control the Arduino.

EXAMPLES OF STRUCTURES

Semicolon ( ; ) – Used to end a statement
Comment - Lines within the code that are ignored by the program and are generally used for notes with important information that the programmer includes either as a reminder to him/her self or another programmer. Placing two forward slashes ( // ) at the beginning of the line will indicate that the line should be skipped. If the note covers multiple lines then a /* indicates the start of the comment and */ the end.
Setup () – This function is called when a sketch starts. Use it to initialize variables, pin modes, start using libraries, etc. The setup function will only run once, after each power up or reset of the Arduino board.
Loop () - This function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond. Use it to actively control the Arduino board.
Curly Braces { } – These are used to surround a set of instructions and must always be used in pairs. These are extremely important to how the code is read and executed by the computer. Missing, extra, or misplaced curly braces can cause many errors which can then be difficult to find.
Conditional Statement – This is a statement that evaluates data and then decides which step to perform next based on the value(s) of the variable(s).
IF – When used in conjunction with a comparison operator, tests whether a certain condition has been reached, such as an input being above a certain number.
Comparison Operator – Indicates which comparison type to evaluate. Some examples include:
== Equal to x == y
!= Not equal to x != y
Else - This is followed by a set of instructions to use when the conditional statement in the example above is False.

Example: IF weather == rain I will wear my raincoat, ELSE I will wear my sweatshirt.

EXAMPLES OF VALUES

Void - The void keyword is used only in function declarations. It indicates that the function is expected to return no information to the function from which it was called.
Boolean – A data type that takes up one byte and holds one of two values, True or False
Const – A keyword that stands for constant. It is a variable qualifier that modifies the behavior of the variable, making a variable "read-only". This means that the variable can be used just as any other variable of its type, but its value cannot be changed.
Int – A data type that is an integer (whole number).
HIGH – If the pin is set to OUTPUT, a HIGH setting tells the machine to send a 3.3V or 5V signal, depending on the board. If the pin is set to INPUT, then it is reading a voltage greater than 2.0V or 3.0V, again depending on the board being used.
LOW – If the pin is set to OUTPUT, a LOW setting tells the machine to ground the pin and send 0V. If the pin is set to INPUT, then it is reading a voltage less than 1.0V or 1.5V, depending on the board being used.

EXAMPLES OF FUNCTIONS

pinMode() - Configures the specified pin to behave either as an input or an output.
digitalWrite() – Write a HIGH or LOW value to a digital pin.
digitalRead() - Reads the value from a specified digital pin, either HIGH or LOW.