What is Arduino?
Arduino is an open-source electronics platform based on easy-to-use hardware and software. Arduino boards are able to read inputs — light on a sensor, a finger on a button, or a Twitter message — and turn it into an output — activating a motor, turning on an LED, publishing something online. You can tell your board what to do by sending a set of instructions to the microcontroller on the board. To do so you use the Arduino programming language (based on Wiring), and the Arduino Software (IDE), based on Processing.
Over the years Arduino has been the brain of thousands of projects, from everyday objects to complex scientific instruments. A worldwide community of makers — students, hobbyists, artists, programmers, and professionals — has gathered around this open-source platform, their contributions have added up to an incredible amount of accessible knowledge that can be of great help to novices and experts alike.
Arduino was born at the Ivrea Interaction Design Institute as an easy tool for fast prototyping, aimed at students without a background in electronics and programming. As soon as it reached a wider community, the Arduino board started changing to adapt to new needs and challenges, differentiating its offer from simple 8-bit boards to products for IoT applications, wearable, 3D printing, and embedded environments.
Thanks to its simple and accessible user experience, Arduino has been used in thousands of different projects and applications. The Arduino software is easy-to-use for beginners, yet flexible enough for advanced users. It runs on Mac, Windows, and Linux. Teachers and students use it to build low cost scientific instruments, to prove chemistry and physics principles, or to get started with programming and robotics. Designers and architects build interactive prototypes, musicians and artists use it for installations and to experiment with new musical instruments. Makers, of course, use it to build many of the projects exhibited at the Maker Faire, for example. Arduino is a key tool to learn new things. Anyone — children, hobbyists, artists, programmers — can start tinkering just following the step by step instructions of a kit, or sharing ideas online with other members of the Arduino community.
There are many other microcontrollers and microcontroller platforms available for physical computing. Parallax Basic Stamp, Netmedia’s BX-24, Phidgets, MIT’s Handyboard, and many others offer similar functionality. All of these tools take the messy details of microcontroller programming and wrap it up in an easy-to-use package. Arduino also simplifies the process of working with microcontrollers, but it offers some advantage for teachers, students, and interested amateurs over other systems:
Inexpensive — Arduino boards are relatively inexpensive compared to other microcontroller platforms. The least expensive version of the Arduino module can be assembled by hand, and even the pre-assembled Arduino modules cost less than \$50
Cross-platform — The Arduino Software (IDE) runs on Windows, Macintosh OSX, and Linux operating systems. Most microcontroller systems are limited to Windows.
Simple, clear programming environment — The Arduino Software (IDE) is easy-to-use for beginners, yet flexible enough for advanced users to take advantage of as well. For teachers, it’s conveniently based on the Processing programming environment, so students learning to program in that environment will be familiar with how the Arduino IDE works.
Open source and extensible software — The Arduino software is published as open source tools, available for extension by experienced programmers. The language can be expanded through C++ libraries, and people wanting to understand the technical details can make the leap from Arduino to the AVR C programming language on which it’s based. Similarly, you can add AVR-C code directly into your Arduino programs if you want to.
Open source and extensible hardware — The plans of the Arduino boards are published under a Creative Commons license, so experienced circuit designers can make their own version of the module, extending it and improving it. Even relatively inexperienced users can build the breadboard version of the module in order to understand how it works and save money.
How do I use Arduino?
See the getting started guide. If you are looking for inspiration you can find a great variety of Tutorials on Arduino Project Hub.
The text of the Arduino getting started guide is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the guide are released into the public domain.
Introduction to the Arduino Programming Language
How can you write programs for your Arduino board? Arduino, natively, supports a language that we call the Arduino Programming Language, or Arduino Language.
Published Jan 24 2020
How can you write programs for your Arduino board?
Arduino, natively, supports a language that we call the Arduino Programming Language, or Arduino Language.
This language is based upon the Wiring development platform, which in turn is based upon Processing, which if you are not familiar with, is what p5.js is based upon. It’s a long history of projects building upon other projects, in a very Open Source way. The Arduino IDE is based upon the Processing IDE, and the Wiring IDE which builds on top of it.
When we work with Arduino we commonly use the Arduino IDE (Integrated Development Environment), a software available for all the major desktop platforms (macOS, Linux, Windows), which gives us 2 things: a programming editor with integrated libraries support, and a way to easily compile and load our Arduino programs to a board connected to the computer.
The Arduino Programming Language is basically a framework built on top of C++. You can argue that it’s not a real programming language in the traditional term, but I think this helps avoiding confusion for beginners.
A program written in the Arduino Programming Language is called sketch. A sketch is normally saved with the .ino extension (from Ardu ino ).
The main difference from “normal” C or C++ is that you wrap all your code into 2 main functions. You can have more than 2, of course, but any Arduino program must provide at least those 2.
One is called setup() , the other is called loop() . The first is called once, when the program starts, the second is repeatedly called while your program is running.
We don’t have a main() function like you are used to in C/C++ as the entry point for a program. Once you compile your sketch, the IDE will make sure the end result is a correct C++ program and will basically add the missing glue by preprocessing it.
Everything else is normal C++ code, and as C++ is a superset of C, any valid C is also valid Arduino code.
One difference that might cause you troubles is that while you can spawn your program over multiple files, those files must all be in the same folder. Might be a deal breaking limitation if your program will grow very large, but at that point it will be easy to move to a native C++ setup, which is possible.
Part of the Arduino Programming Language is the built-in libraries that allow you to easily integrate with the functionality provided by the Arduino board.
Your first Arduino program will surely involve making a led turn on the light, and then turn off. To do so, you will use the pinMode() , delay() and digitalWrite() functions, along with some constants like HIGH , LOW , OUTPUT .
Like this, the canonical first Arduino project (the “Hello, World!”):
This is all part of the Arduino Programming Language, or we’d better call it suite or library.
Support for other language
As a reminder, I want to note that you are not limited to using this language and IDE to program an Arduino. Projects exist, among others, to let you run Node.js code on it using the Johnny Five project, Python code using pyserial and Go code with Gobot, but the Arduino Programming Language is definitely the one you’ll see most tutorials based upon, since it’s the native and canonical way to work with these devices.
The Arduino Programming Language Built-in constants
Arduino sets two constants we can use to
HIGH equates to a high level of voltage, which can differ depending on the hardware (>2V on 3.3V boards like Arduino Nano, >3V on 5V boards like Arduino Uno) LOW equates to a low level of voltage. Again, the exact value depends on the board used
Then we have 3 constants we can use in combination with the pinMode() function:
- INPUT sets the pin as an input pin
- OUTPUT sets the pin as an output pin
- INPUT_PULLUP sets the pin as an internal pull-up resistor
The other constant we have is LED_BUILTIN , which points to the number of the on-board pin, which usually equates to the number 13 .
In addition to this, we have the C/C++ constants true and false .
Arduino Math Constants
- M_PI the constant pi ( 3.14159265358979323846 )
- M_E the constant e
- M_LN10 the natural logarithm of the number 10.
- M_LN2 the natural logarithm of the number 2.
- M_LOG10E the logarithm of the e to base 10.
- M_LOG2E the logarithm of the e to base 2.
- M_SQRT2 the square root of 2.
- NAN the NAN (not a number) constant.
The Arduino Programming Language Built-in Functions
In this section I am going to make a reference for the built-in functions provided by the Arduino Programming Language.
- setup() this function is called once, when the program starts, and when the Arduino is shut down and restarted.
- loop() this function is repeatedly called while the Arduino program is running.
The following functions help with handling input and output from your Arduino device.
- digitalRead() reads the value from a digital pin. Accepts a pin number as a parameter, and returns the HIGH or LOW constant.
- digitalWrite() writes a HIGH or LOW value to a digital output pin. You pass the pin number and HIGH or LOW as parameters.
- pinMode() sets a pin to be an input, or an output. You pass the pin number and the INPUT or OUTPUT value as parameters.
- pulseIn() reads a digital pulse from LOW to HIGH and then to LOW again, or from HIGH to LOW and to HIGH again on a pin. The program will block until the pulse is detected. You specify the pin number and the kind of pulse you want to detect (LHL or HLH). You can specify an optional timeout to stop waiting for that pulse.
- pulseInLong() is same as pulseIn() , except it is implemented differently and it can’t be used if interrupts are turned off. Interrupts are commonly turned off to get a more accurate result.
- shiftIn() reads a byte of data one bit at a time from a pin.
- shiftOut() writes a byte of data one bit at a time to a pin.
- tone() sends a square wave on a pin, used for buzzers/speakers to play tones. You can specify the pin, and the frequency. It works on both digital and analog pins.
- noTone() stops the tone() generated wave on a pin.
- analogRead() reads the value from an analog pin.
- analogReference() configures the value used for the top input range in the analog input, by default 5V in 5V boards and 3.3V in 3.3V boards.
- analogWrite() writes an analog value to a pin
- analogReadResolution() lets you change the default analog bits resolution for analogRead() , by default 10 bits. Only works on specific devices (Arduino Due, Zero and MKR)
- analogWriteResolution() lets you change the default analog bits resolution for analogWrite() , by default 10 bits. Only works on specific devices (Arduino Due, Zero and MKR)
- delay() pauses the program for a number of milliseconds specified as parameter
- delayMicroseconds() pauses the program for a number of microseconds specified as parameter
- micros() the number of microseconds since the start of the program. Resets after
70 minutes due to overflow
millis() the number of milliseconds since the start of the program. Resets after
50 days due to overflow
- abs() the absolute value of a number
- constrain() constrains a number to be within a range, see usage
- map() re-maps a number from one range to another, see usage
- max() the maximum of two numbers
- min() the minimum of two numbers
- pow() the value of a number raised to a power
- sq() the square of a number
- sqrt() the square root of a number
- cos() the cosine of an angle
- sin() the sine of an angle
- tan() the tangent of an angle
Note: there are more built-in mathematical functions if you need them, documented here.
Working with alphanumeric characters
- isAlpha() checks if a char is alpha (a letter)
- isAlphaNumeric() checks if a char is alphanumeric (a letter or number)
- isAscii() checks if a char is an ASCII character
- isControl() checks if a char is a control character
- isDigit() checks if a char is a number
- isGraph() checks if a char is a printable ASCII character, and contains content (it is not a space, for example)
- isHexadecimalDigit() checks if a char is an hexadecimal digit (A-F 0-9)
- isLowerCase() checks if a char is a letter in lower case
- isPrintable() checks if a char is a printable ASCII character
- isPunct() checks if a char is a punctuation (a comma, a semicolon, an exclamation mark etc)
- isSpace() checks if a char is a space, form feed \f , newline \n , carriage return \r , horizontal tab \t , or vertical tab \v .
- isUpperCase() checks if a char is a letter in upper case
- isWhitespace() checks if a char is a space character or an horizontal tab \t
Random numbers generation
- random() generate a pseudo-random number
- randomSeed() initialize the pseudo-random number generator with an arbitrary initial number
In Arduino, like in most languages, it’s impossible to get really random numbers, and the sequence is always the same, so you seed it with the current time or (in the case of Arduino) you can read the input from an analog port.
Everything You Need to Know About Arduino Code
Since the launch of the Arduino open-source platform, the brand has established themselves at the center of an expansive open-source community. The Arduino ecosystem is comprised of a diverse combination of hardware and software. The versatility of Arduino and its simple interface makes it a leading choice for a wide range of users around the world from hobbyists, designers, and artists to product prototypes.
The Arduino board is connected to a computer via USB, where it connects with the Arduino development environment (IDE). The user writes the Arduino code in the IDE, then uploads it to the microcontroller which executes the code, interacting with inputs and outputs such as sensors, motors, and lights.
Both beginners and experts have access to a wealth of free resources and materials to support them. Users can look up information on how to set up their board or even how to code on Arduino. The open source behind Arduino has made it particularly friendly to new and experienced users. There are thousands of Arduino code examples available online. In this post, we’ll take you through some basic principles of coding for Arduino.
Arduino Coding Environment and basic tools
What language is Arduino?
Arduino code is written in C++ with an addition of special methods and functions, which we’ll mention later on. C++ is a human-readable programming language. When you create a ‘sketch’ (the name given to Arduino code files), it is processed and compiled to machine language.
The Arduino Integrated Development Environment (IDE) is the main text editing program used for Arduino programming. It is where you’ll be typing up your code before uploading it to the board you want to program. Arduino code is referred to as sketches.
Note: It’s important to use the latest version of Arduino IDE. From time to time, check for updates here.
Arduino code example
As you can see, the IDE has a minimalist design. There are only 5 headings on the menu bar, as well as a series of buttons underneath which allow you to verify and upload your sketches. Essentially, the IDE translates and compiles your sketches into code that Arduino can understand. Once your Arduino code is compiled it’s then uploaded to the board’s memory.
All the user has to do to start compiling their sketch is press a button (a guide to this can be found below).
If there are any errors in the Arduino code a warning message will flag up prompting the user to make changes. Most new users often experience difficulty with compiling because of Arduino’s stringent syntax requirements. If you make any mistakes in your punctuation when using Arduino, the code won’t compile and you’ll be met with an error message.
Serial Monitor and Serial Plotter
Arduino serial monitor can be opened by clicking on the magnifying glass icon on the upper right side of the IDE or under tools. The serial monitor is used mainly for interacting with the Arduino board using the computer, and is a great tool for real-time monitoring and debugging. In order to use the monitor, you’ll need to use the Serial class.
The code you download from circuito.io has a test section that helps you test each components using the serial monitor, as you can see in the screenshot below:
Arduino serial plotter is another component of the Arduino IDE, which allows you to generate a real-time graph of your serial data. The serial plotter makes it much easier for you to analyze your data through a visual display. You’re able to create graphs, negative value graphs, and conduct waveform analysis.
Debugging Arduino Code and Hardware
Unlike other software programming platforms, Arduino doesn’t have an onboard debugger. Users can either use third-party software, or they can utilize the serial monitor to print Arduino’s active processes for monitoring and debugging.
By using the Serial class, you can print to the serial monitor, debugging comments and values of variables. On most Arduino models, this will be using serial pins 0 and 1 which are connected to the USB port.
In Arduino, much like other leading programming platforms, there are built-in libraries that provide basic functionality. In addition, it’s possible to import other libraries and expand the Arduino board capabilities and features. These libraries are roughly divided into libraries that interact with a specific component or those that implement new functions.
To import a new library, you need to go to Sketch > Import Library
In addition, at the top of your .ino file, you need to use ‘#include’ to include external libraries. You can also create custom libraries to use in isolated sketches.
To use the Arduino pins, you need to define which pin is being used and its functionality. A convenient way to define the used pins is by using:
‘#define pinName pinNumber’.
The functionality is either input or output and is defined by using the pinMode () method in the setup section.
Whenever you’re using Arduino, you need to declare global variables and instances to be used later on. In a nutshell, a variable allows you to name and store a value to be used in the future. For example, you would store data acquired from a sensor in order to use it later. To declare a variable you simply define its type, name and initial value.
It’s worth mentioning that declaring global variables isn’t an absolute necessity. However, it’s advisable that you declare your variables to make it easy to utilize your values further down the line.
In software programming, a class is a collection of functions and variables that are kept together in one place. Each class has a special function known as a constructor, which is used to create an instance of the class. In order to use the functions of the class, we need to declare an instance for it.
Every Arduino sketch must have a setup function. This function defines the initial state of the Arduino upon boot and runs only once.
Here we’ll define the following:
- Pin functionality using the pinMode function
- Initial state of pins
- Initialize classes
- Initialize variables
- Code logic
The loop function is also a must for every Arduino sketch and executes once setup() is complete. It is the main function and as its name hints, it runs in a loop over and over again. The loop describes the main logic of your circuit.
Note: The use of the term ‘void’ means that the function doesn’t return any values.
How to program Arduino
The basic Arduino code logic is an “if-then” structure and can be divided into 4 blocks:
Setup — will usually be written in the setup section of the Arduino code, and performs things that need to be done only once, such as sensor calibration.
Input — at the beginning of the loop, read the inputs. These values will be used as conditions (“if”) such as the ambient light reading from an LDR using analogRead().
Manipulate Data — this section is used to transform the data into a more convenient form or perform calculations. For instance, the AnalogRead() gives a reading of 0-1023 which can be mapped to a range of 0-255 to be used for PWM.(see analogWrite())
Output — this section defines the final outcome of the logic (“then”) according to the data calculated in the previous step. Looking at our example of the LDR and PWM, turn on an LED only when the ambient light level goes below a certain threshold.
Arduino Code libraries
A library is a folder comprised of files with C++ (.cpp) code files and C++ (.h) header files.
The .h file describes the structure of the library and declares all its variables and functions.
The .cpp file holds the function implementation.
The first thing you need to do is find the library you want to use out of the many libraries available online. After downloading it to your computer, you just need to open Arduino IDE and click on Sketch > Include Library > Manage Libraries. You can then select the library that you want to import into the IDE. Once the process is complete the library will be available in the sketch menu.
In the code provided by circuito.io instead of adding external libraries like mentioned before, we provide them with the firmware folder. In this case, the IDE knows how to find them when using #include.
From Software to Hardware
There is a lot to be said of Arduino’s software capabilities, but it’s important to remember that the platform is comprised of both software and hardware. The two work in tandem to run a complex operating system.
Code → Compile → Upload → Run
At the core of Arduino, is the ability to compile and run the code.
After writing the code in the IDE you need to upload it to the Arduino. Clicking the Upload button (the right-facing arrow icon), will compile the code and upload it if it passed compilation. Once your upload is complete, the program will start running automatically.
You can also do this step by step:
- First, compile the code. To do this simply click the check icon (or click on sketch > Verify / Compile in the menu bar.
As you can see, the check icon is located in the top left underneath the “File” tag in the menu section.
Once you’ve done this, Arduino will start to compile. Once it’s finished, you’ll receive a completion message that looks like this:
As you can see, the green line at the bottom of the page tells you that you’re “done compiling”. If your code fails to run, you’ll be notified in the same section, and the problematic code will be highlighted for editing.
Once you’ve compiled your sketch, it’s time to upload it.
- Choose the serial port your Arduino is currently connected to. To do this click on Tools > Serial port in the menu to designate your chosen serial port (as shown earlier above). You can then upload the compiled sketch.
- To upload the sketch, click on the upload icon next to the tick. Alternatively you can go the the menu and click File> upload. Your Arduino LEDS will flicker once the data is being transferred.
Once complete, you’ll be greeted with a completion message that tells you Arduino has finished uploading.
Setting Up Your IDE
In order to connect an Arduino board to your computer you need a USB cable. When using the Arduino UNO, the USB transfers the data in the program directly to your board. The USB cable is used to power your arduino. You can also run your Arduino through an external power source.
Before you can upload the code, there are some settings that you need to configure.
Choose your board — You need to designate which Arduino board you’re going to be using. Do this by click Tools > Board > Your Board.
Choose your processor- there are certain boards (for example Arduino pro-mini) for which you need to specify which processor model you have. Under tools > processor > select the model you have.
Choose your port — to select the port to which your board is connected, go to tools > Port > COMX Arduino (This is Arduino’s serial port).
How to Install Non-Native Boards (e.g. NodeMCU)
Some board models are not pre-installed in the Arduino IDE, therefore you’ll need to install them before you can upload code.
To install a non-native board such as NodeMCU, you need to:
- Click on tools > Boards > Boards Manager
- Search for the board you want to add in the search bar and click “install”.
Some boards cannot be found through the Board Manager. In this case, you’ll need to add them manually. In order to do this:
- Click on Files > Preferences
- In the Additional Boards Manager field, paste the URL of the installation package of your board. For instance, for nodeMCU, add the following URL: http://arduino.esp8266.com/stable/package_esp8266com_index.json
- Click OK
- Go to tools > Boards > Boards Manager
- Search for the board you want to add in the search bar and click “install”.
Once you’ve completed this step, you will see the installed boards in the boards’ list under tools.
Note: the process may differ slightly for different boards.
Arduino: An Extremely Versatile Platform
Arduino is far more than just a simple microcontroller. With an expansive IDE and a vast array of hardware configurations, Arduino is truly a diverse platform. The variety of its libraries and its intuitive design makes it a favorite for new users and experienced makers alike. There are thousands of community resources to help you get started with both hardware and software.
As you advance your skills, you may face problems that require debugging, which is a weak spot of the Arduino IDE. Luckily, there are several tools and methods to debug Arduino hardware and software. In the next article, we’re going to look at how to debug Arduino (and how to test Arduino code) as well as how to use simulators and emulators.