Arduino Debugging and Testing

How to test your Arduino code ?

The testing of the software and hardware is carried out in several steps. During code programming, the programmer can check the syntax errors using the compiler directly in the Arduino IDE (using Verify button). However, this syntax error check does not give any indication of incorrect structuring or sequence of the program.

Testing the correct sequence of the code should be done directly on the board with external components connected. However, it’s a good idea to perform a hardware test for each component by writing small test programs for each external component individually.

By connecting all hardware parts and running the whole program for the first time, the first important test is done. Often the built solution does not run or runs partially faulty during the first tests. Now the debugging of the individual actions and functions of the program begins.

The display of individual variable values or signal states within the program sequence can be realized using the serial monitor by outputting the desired values to the serial interface. In the console the data are displayed during the program run and support the programmer in troubleshooting.

What is Arduino serial monitor ?

The serial monitor is a useful tool within the Arduino IDE and allows the display of the transmitted data via the serial port. When you open the Serial monitor, via the toolbar or Tools->Serial Monitor, a new window opens a new window without any content.

Serial Monitor

The serial monitor can now be used to receive data from the Arduino or to send data. To show data from the Arduino on the serial monitor, the Arduino Board must execute serial print instruction as shown in the example below.

void setup()
  // Initialize serial at baudrate of 9600

void loop()
  Serial.println("Hallo world");

Serial.begin(9600); instruction initialize the serial transmission with a transmission rate (called baud rate) of 9600 bits per second. This should match the baud rate on the serial monitor window in order to see sent data.

char letter = '0';

void setup()
  // Initialize serial at baudrate of 9600
void loop() {
  if (Serial.available() > 0){
    letter =;
    if(letter == 'A'){
      Serial.println("Letter is A");
    else if(letter == 'B'){
      Serial.println("Letter is B");

Serial.begin(9600); instruction initialize the serial transmission with a transmission rate (called baud rate) of 9600 bits per second. This should match the baud rate on the serial monitor window in order to see sent data.

To receive the data from the Arduino board, the instruction Serial.println( ); is used to print out what’s inside the brackets on the serial monitor. For sending data from the serial monitor, write a text in the input field and press the button Send or press Enter.

How debug Arduino code ?

Where programming is done, errors occur. You will notice this quickly when you first lines of code for your Arduino board. A missing semicolon or a forgotten declaration and the IDE complains when compiling the program code. With smaller projects, you usually found the error quickly and fixed it then recompile again. Such errors are called compile errors.

But an error does not necessarily mean a missing semicolon or a typo in the code. Another type of error is called runtime error, where your program compiled successfully but your project does not work as expected.

Possible causes can vary: In the program structure a function is not called, a wrong formula used in the calculations, or even a variable declared with a wrong data type.

The approach to look deeper into the code to find the error is called debugging. The first important step is to make sure that the external components like a sensor or limit switch are wired properly. Second, check that they deliver correct values or signals. This can be tested using small sketches to check that they are functioning correctly.

Another way is to inject debugging instruction inside the code. One example is to use Serial print to print out sensor values or Computation output on the serial monitor. This way you can see what and where is things going wrong.

#define DEBUG

#define SENSOR_PIN  A0  // Sensor analog input pin 
#define PWM_PIN       9      // PWM output pin

int valSensor= 0;        // variable for sensor value
int valPwm= 0;        // variable for PWM output value

void setup()
  // Initialize serial at baudrate of 9600
  #ifdef DEBUG
    Serial.println("Debugging aktiviert");


void loop()

   // read the sensor value
  valSensor= analogRead(SENSOR_PIN);
  // map to PWM range
  valPwm= map(valSensor, 0, 1023, 0, 255);
  // Update the PWM value:
  analogWrite(PWM_PIN, valPwm);

  #ifdef DEBUG
    // Print on the Serial Monitor:
    Serial.print("sensor value = ");
    Serial.print("t PWM output value = ");

  // wait 500 milliseconds

By defining DEBUG, the values can be checked on the serial monitor. Once done with debugging, undefine DEBGU (replace #define with #undef) and no output is sent to the serial port.

Digital states can be visualized not only by the output on the serial monitor but also using LEDs. For this purpose, connect an LED and series resistors on the required port of the Arduino board. Then the LED will turn-on or off according to the actual voltage on the ouput pin.

Read More

Arduino Functions

What are functions in Arduino

A function is a closed unit within a program and is called by its name. Usually with the function call still values are passed, which are processed then within the function. These values are called “parameters”. After execution of the function, which can be a calculation, a conversion or a signal output to an output port, this “small program” is executed and the main program, which called the function, is continued.

Often, however, the called function returns a response (called function return). This can be the result of a calculation or a status of a state.

Function Structure

The structure of the function is as follows:

Type FunctionName (type parameter){
//Function body
rerun val;

An example looks like this:

Function Structure

The type of a function indicates what kind of value is returned from the function. This can be int, char, etc. Accordingly, the data type of this return value is specified in the call of the function before the function name. The call of a function is usually made from the main program.

Function Example in Arduino

Program 1

Program 1 shows the call of the function sensorRead from the main program (loop). The return value is the analog value with the int data type. For a fun.ction that does not have a return value, the keyword void is used for the type designation.

Program 2

In Program 2, the loop calls the function sensorReadPrintSerial which has no return value and no input parameter. Consequently, this it calls another function printVal, which has an input parameter an no return.  

Read More

Arduino – Variables and Data types

Arduino Variables

In programming, values that are stored for further processing are named with a single word called a variable. The value of a variable can change continuously or be changed by the program. The variable name should be chosen in such a way that it is easily readable and understandable within the program. In addition, a variable also has a data type that defines the value range.

The Variable must be declared before being used. So the data type, the variable name and the value of the variable are set. If no value is specified, the variable value is set to 0.

datatype Variable_Name =Value;


int motorSpeed = 255;

Comprehensible variable names such as motorSpeed or temperatureSensor improve the readability of th program

Arduino Datatypes

A data type describes the value range and the possible operations of a variable. Since the data types of the variables require different amounts of memory, you must be aware of exactly which possible values a variable defined can have when creating the program: Is it only a digital state with the values yes and no or can the variable hold an entire text? The data type must be selected accordingly. The most important data types and their value ranges for creating Arduino programs are listed below:

Data typeValue range    Memory requirement  Explanations/Notes    Examples
booleantrue/false1 byteValue for Yes/No or On/Off,  boolean machineStatus = true;  
int-32,768 to 32,7672 bytes  Integer values for values without decimal places  int potiValue = 1023;  
unsigned int  0 to 4,294,967,295    2 bytesInteger for positive values without decimal places  int tempValue = -5;  
byte0 to 2551 byteLow values (and correspondingly small memory requirements)    byte brightnessLED = 126;  
wordUnsigned 16-bit or 32-bit16-bit on Atmega boards.
32-bit on Due and Zero
Be aware of processor usedword value = 1500;
long-2,147,483,648 to 2,147,483,6474 bytesInteger numbers with big values        long offset = -15362;  
unsigned long0 to 4,294,967,2954 bytesUnsigned Integer numbers with big values  unsigned long secondsPassed = 45379;
float-3.4028235E+38 to 3.4028235E+384 bytesValues with decimal places  float voltageValue = 3.3;  
double-3.4028235E+38 to 3.4028235E+384 bytes-3.4028235E+38 to 3.4028235E+38double distanceGPS= 722.54;  
char  -128 to 127  1 byteValue for storing one character  char charR = ‘R’;  
unsigned char  0 to 2551 byteUsually used with numbers having range 0 to 255unsigned char charNumber = 255;
stringlength depends on definitiondepends on needStrings like texts or several charactersstring brand[ ] = “ROBOSANS”;
arraysize depends to definitionDepends on array sizestore values in variables with table form like e.g. lists of ports or configuration valuesint portsPWM[ ] = {3,5,6,9,10,11};
Read More

Arduino Sketch

What are Arduino sketches?

The code that runs on Arduino is usually called “Sketch”. Getting started with Arduino programming is quite easy because the structure of the Sketches is clear. The Arduino programming language is derived from C++ programming. You only need a few lines of code for your first simple projects.

Arduino Program Structure

The structure of an Arduino program is divided into two parts: setup() and loop().

Arduino Sketch Structure

The setup function is executed only once when the Arduino board is started or after a reset. In this function basic settings like variable declarations, the configuration of ports, or initialization routines. Additionally, the inputs and outputs are set, as shown in the Blink example below, the led pin 13 is set as output.

The setup function is mandatory and must always be present, even if no declarations have to be made. In this case, the function remains empty.

The loop function is the second area of the basic structure of an Arduino program and has the task of the main program. After the setup function has been executed once, the loop function is run through – as its name implies, as an endless loop. In the loop, all further instructions and function calls are accommodated, which are needed in the normal operation for the desired application. As in the blinking example, it turns on the LED, waits one second, turns it off, waits one second, and repeats forever.

Arduino Examples

The easiest way to get started is to work through example programs and then modify and extend them for your own applications. Also, you can find a lot of Arduino sketches and even complete projects for your application on the internet. One Arduino code example is called AnalogInOutSerial shown above.

AnalogInOutSerial Arduino example

It sets the pulse width modulation (PWM) of an output pin (9) based on the analog input readings on pin (A0), after mapping from the ADC scale (0 to 1023) to the output PWM scale (0 to 255). It also prints out the results on the Serial Monitor. The circuit diagram for this code is shown below

Read More

Software and Hardware Setup

Software Setup

For the development of the Arduino programs, the Arduino integrated development environment (IDE) should be installed on the local computer. It can be downloaded free of charge from the Arduino website. The Arduino IDE is a complete development environment containing code editor, documentation and a number of examples as well as standard libraries.

In addition, a USB driver must be installed and configured. This driver enables the USB port to communicate as a serial port with the FTDI chip on the Arduino board. The software is available in the archive file of the development environment and must be installed after the installation of the development environment.

Connecting the Arduino to the IDE

Communication between the IDE takes place via the virtual COM port that has been set up, using the USB interface as the physical transmission medium.

  1. Connect the Arduino to the computer via a standard USB. After connection, power supply is applied to the board from the USB interface.
  1. Open the Arduino IDE. Select the Arduino board via the menu item Tools->Board.
  1. Select the serial port (COM port) via the menu item Tools->Port. Note that the serial port to be used only appears in the listing if the Arduino board is connected to the computer via USB cable.

LED blinking code

For the first function test and the first executable Arduino program, various example programs are already stored in the IDE.

  1. Open the Blink program via Files->Examples->Basics. This test program controls the digital output port 13 of the Arduino (an LED is already connected on the board), blinks every second.
  2. Compile the program via the menu item Sketch->Verify/Compile.
  3. Upload the code to the Arduino’s microcontroller via Sketch->Upload into the microcontroller on the Arduino board.

Another way to compile (Verify) and upload the code is to use the symbols: to verify and to upload.

Read More

Arduino Uno

The Arduino Uno is the standard board of the Arduino which was introduced at the New York Maker Faire in September 2010.

On the Arduino Uno the following connectors are standard:

USB socket: The USB port (type B) is used for programming via the development environment and for communication with the connected computer. At the same time the board can be powered via the USB port.

Socket for external power supply: The Arduino board can be supplied with an external power supply or battery via a 2.1 mm socket. The power supply via the USB port is automatically deactivated. A particular advantage is the higher power that can be drawn from the external supply voltage, for example to supply actuators and sensors. In case of a short-circuit, it is not the USB port of the connected computer that is loaded, but the overload protection of the external power supply.

Connector strips for digital inputs and outputs: Single-row connector sockets that can be plugged into the extension boards (shields) or connector strips. All existing ports and interfaces are available via these connector strips.

ICSP: The pin row for the ICSP (In-Circuit Serial Programming) allows programming of sketches (programs) without bootloader by means of an external programming device.

DescriptionDetailed data
Power supply7-12 VDC
Operating voltage5 VDC and 3.3 VDC (internally generated by voltage regulator)
Digital inputs/outputs14 (6 of them as PWM outputs)
Analog inputs6
Current per digital pin40 mA DC
Flash memory32 KB (ATmega328), where 0,5 KB are occupied by the bootloader
SRAM2 KB (ATmega328)  
EEPROM1 KB (ATmega328)
Clock frequency16 MHz
USB interfaceyes
Reset switchyes

Read More

Arduino Board

The Arduino is an open-source embedded development platform that consists of both hardware and software. The hardware part consists of a microcontroller chip and its operating circuit. It has analog and digital inputs and outputs that connect the Arduino to the physical world.

The software part consists of an Integrated Development Environment (IDE), bootloader, and a huge set of libraries, an executable program that runs on the PC to create the code and upload to the Arduino, which is then executed by the hardware part. The Arduino’s programming language is based on C++ and is designed so that one can create programs without too deep programming knowledge.

The created program is called “Sketch”. The IDE uploads the sketch via USB port from the development environment into the flash memory of the Arduino’s microcontroller. This USB connection to the hardware part must always be present during the development and testing phase. The data transfer is done as a serial data transfer. At the same time, the connection also serves as an aid for debugging. With the help of a “serial monitor”, the states of the inputs and outputs ports can be monitored. After development, the connection to the development environment can be disconnected and the Arduino can communicate with the real world independently as long as it is connected to the power.

The “board” refers to the various versions of the Arduino’s printed circuit boards equipped with components. Different Arduino boards can be selected based on the application. Each board contains different microcontroller, connectors, and interfaces.

Power is supplied either by a separate, external power supply unit or via the connected USB interface. The USB interface can deliver a maximum of 500 mA at 5 Volt voltage. For smaller own developments this kind of power supply is usually sufficient. Besides the power supply just described, the USB interface is also used for communication with the development environment, i.e. for uploading programs (sketches) and reading/sending data via serial monitor.

Read More