Home IoT & Hardware Practical Arduino Robotics

Practical Arduino Robotics

By Lukas Kaul
ai-assist-svg-icon Book + AI Assistant
eBook + AI Assistant $27.99 $18.99
Print $34.99
Subscription $15.99 $10 p/m for three months
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
eBook + AI Assistant $27.99 $18.99
Print $34.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Introducing Robotics and the Arduino Ecosystem
About this book
Every robot needs a “brain,” and the Arduino platform provides an incredibly accessible way to bring your Arduino robot to life. Anyone can easily learn to build and program their own robots with Arduino for hobby and commercial uses, making Arduino-based robots the popular choice for school projects, college courses, and the rapid prototyping of industrial applications! Practical Arduino Robotics is a comprehensive guide that equips you with the necessary skills and techniques that can be applied to various projects and applications, from automating repetitive tasks in a laboratory to building engaging mobile robots. Building on basic knowledge of programming and electronics, this book teaches you how to choose the right components, such as Arduino boards, sensors, and motors, and write effective code for your robotics project, including the use of advanced third-party Arduino libraries and interfaces, such as Analog, SPI, I2C, PWM, and UART. You'll also learn different ways to command your robots wirelessly, such as over Wi-Fi. Finally, with basic to advanced project examples, this book illustrates how to build exciting autonomous robots like a self-balancing telepresence robot. By the end of this book, you'll be able to design and create your own custom robots for a wide variety of applications.
Publication date:
March 2023
Publisher
Packt
Pages
334
ISBN
9781804613177

 

Introducing Robotics and the Arduino Ecosystem

Creating robots means building machines that autonomously interact with the physical world. Robotics lies right at the intersection of three exciting engineering fields: computer science, electrical engineering, and mechanical engineering. Building your own robots can seem daunting, even if you are an expert in any of these three fields already. There is a lot to know before you cwan really get started. But if you successfully master the fundamental skills that this book teaches you, you will soon be ready to create advanced robots yourself. And from there, the possible applications are endless! You can build robots just for fun and the joy of learning more and more with every project. Or you can use these skills to quickly create a physical prototype of a product idea, build smart tools that help you at home or on the job, and automate, entertain, teach, and educate. You might be able to create amazing student projects or even boost your career with these new skills.

Your robot needs a brain – a computer that can run your programs, process sensor signals, and control motors. There are several options for DIY robots. You can simply use your laptop, but that is a costly and pretty clunky option, and it makes interfacing with low-level hardware and implementing real-time control systems difficult. You can also use the popular Raspberry Pi single-board computer, which is a powerful and affordable platform for many DIY projects. However, for many DIY robot projects, Raspberry Pi is overkill and adds unnecessary layers of complexity. In contrast, using microcontrollers as the compute platform is extremely affordable, makes interfacing with almost any hardware easy, and is a great way to learn about low-level programming and real-time systems. For many DIY robotics projects, microcontrollers are the ideal platform, and this is where Arduino comes in!

Arduino is an ecosystem of microcontroller boards, tools, and software building blocks that makes creating your own advanced robots exceptionally easy. The two core elements of this ecosystem are Arduino boards and the Arduino Integrated Development Environment (IDE). Arduino boards are affordable, capable microcontroller boards that are incredibly easy to use, even if you have never worked with electronics before. These features, combined with their wide availability (thanks to their open source design) have truly made microcontrollers accessible to anyone. The Arduino board will be the brain of your robot, running the program you wrote for it. It will sense the world with sensors and make the motors of your robot move accordingly. The Arduino IDE is what we use to develop the programs for your robots and to transfer them from your computer to the Arduino. The Arduino IDE sits in the sweet spot of microcontroller IDEs between graphical programming languages (drag and drop programming) and highly hardware-specific IDEs provided by microcontroller manufacturers. While the former is easy to master but can be very limiting, the latter gives access to a microcontroller’s full potential at the cost of taking years to master. In contrast, the Arduino IDE embodies the 80/20 principle: it gives us access to roughly 80% of the microcontrollers’ capabilities with only 20% of the effort.

This chapter will kick-start your journey toward building and programming your own robots by answering the following questions:

  • What are the main components of a robot?
  • What is an Arduino microcontroller board?
  • What is the Arduino ecosystem?
  • How do you program your Arduino-based robot?

By the end of this chapter, you will know the answers to all of these questions; you will have successfully set up the Arduino IDE on your computer, and your first Arduino program will be running on your Arduino.

 

Technical requirements

You will need an Arduino (or compatible) microcontroller board and the matching USB cable to connect it to your computer. In this chapter, we will assume that you have an Arduino Uno Rev3, a great Arduino board to start with.

Figure 1.1 – Your computer, a USB cable, and an Arduino Uno are all you need for this chapter

Figure 1.1 – Your computer, a USB cable, and an Arduino Uno are all you need for this chapter

 

The main components of a robot

For the purpose of this book, we will define a robot as a machine that can autonomously and intentionally interact with its environment. This definition directly provides the three key capabilities that a robot must have:

  • Sense its environment
  • Reason about the state of its environment and compute its appropriate reaction
  • Physically move to interact with the environment

Sense-Reason-Act is a commonly cited robotics paradigm and is visualized in Figure 1.2:

Figure 1.2 – The Sense-Reason-Act paradigm of robotics for Arduino robots

Figure 1.2 – The Sense-Reason-Act paradigm of robotics for Arduino robots

A robot needs to sense the aspects of its environment that are relevant to its task. If you build a robot to water your plants, the robot needs to sense the moisture of the soil, for example. If you build an automated transporting robot that needs to follow a line on the floor, it needs to sense the position of the line between its wheels. Choosing the right sensors for your robot is an important step in the design process. This book will introduce you to a variety of readily available and easy-to-use sensor types that work with Arduino robots, along with examples of how to use and integrate them into your robot.

Reasoning, based on sensor signals, is the task of the program that you implement on your Arduino. Your Arduino can run programs just like a real computer, although, typically, with much tighter restrictions on computational power and available memory. We will keep these limitations in mind when we write our Arduino programs. In practice, there is often a trade-off between choosing sensors and implementing the control logic. Adding more and better sensors can make controlling your robot easier, but also leads to more complex hardware and higher cost. More advanced software that runs on your robot can often make up for the lack of high-quality sensor data but is more difficult and time-consuming to develop. An example of this is the combination of the human eye and brain: the eye is not a very good image sensor. It has a blind spot, variable resolution and color sensitivity across its field of view, and a less-than-ideal lens. Yet our brain turns this all but perfect sensor data into crystal clear images under a wide variety of conditions (enabling you to read this book, for example). Here, the capabilities of the software in our brain make up for the rather poor sensor. In contrast, most robots that heavily rely on image data for their tasks (autonomous cars, for example) have very good camera sensors, and they can use this image data without much post-processing.

Your robot will need motors (or more generally, actuators) to physically act. These can be electric motors, pneumatic or hydraulic cylinders, gasoline engines, or even rocket thrusters. In this book, we will focus our attention on electric motors, but let’s keep in mind that there are many more actuator types to explore. In contrast to sensors that can often be directly connected to an Arduino and even powered from it, motors typically need some form of driver (or amplifier) in between the Arduino and the motor. This is because motors tend to require much more power than an Arduino alone can provide. You can imagine the motor as a big and complex piece of machinery, and the driver electronics as the specialist operator of this piece of machinery. The Arduino will communicate with the driver/operator to tell them what the machine should be doing, but it leaves the actual operation of the machine to the operator. There is a similar trade-off between the quality and capabilities of your robot’s actuators and the complexity of the robot program that we mentioned earlier with the sensors. It is generally easier to work with very precise, fast, and strong actuators, but more sophisticated software can often make up for imperfect actuators. The human brain is again a good example: humans can perform incredibly precise and dynamic movements, even though there is quite a bit of latency in our nervous system. The brain’s software can make up for the shortcomings of the hardware.

What different types of robots are there?

There are many types of robots that fall under our broad definition of a robot. The content of this book is relevant for all of them, so no matter whether you want to build a flying robot or your own 3D printer, this book will be very useful for you. In fact, there are so many different kinds and types of robots built for a diverse range of applications that it is not at all straightforward to classify them consistently. At a very high level, it is common to differentiate between mobile robots that can move around in the world and stationary robots. Prominent examples of mobile robots are self-driving cars, and prominent examples of stationary robots are robotic arms widely used in industrial manufacturing, for example, to weld car parts together.

Mobile robots can be divided into subcategories based on whether they are ground-based, flying, or swimming, how they propel themselves (for example, with wheels or legs), and whether they have the means to manipulate their environment with an arm and a gripper. Using these categories, you could describe a humanoid robot (one that looks like a human) as a ground-based, legged, dual-arm, mobile manipulator.

In this book, we will primarily use ground-based, wheeled, mobile robots as examples. This type of robot is easy and inexpensive to build, can be tested virtually everywhere, and exemplifies the key concepts that apply to almost every category of robots.

 

What is an Arduino microcontroller board?

The Arduino ecosystem is a set of microcontroller hardware, software tools, and libraries that make programming microcontrollers much more accessible than it has been traditionally. In this section, we will discuss what microcontrollers are, and how Arduino helps us use them easily and effectively.

What is a microcontroller?

A microcontroller is an integrated circuit (IC) that contains all the necessary components to make it a little standalone computer. An IC is a complex piece of electrical circuitry that is made from a single, tiny piece of silicon (a chip). A microcontroller has a processor (CPU), memory and storage, and usually a host of other hardware peripherals that implement standardized low-level interfaces to other electrical circuits. These interfaces can be used to communicate with other pieces of hardware, such as sensors and motor drivers. To make them easier to work with, manufacturers put the microcontroller IC in a housing that is much larger than the IC itself. The housing exposes metal pins that are connected to the electrical contacts of the IC inside. The terms IC and chip are often used interchangeably to describe the combination of the silicon chip and its housing.

The simplest interface is digital input/output (I/O). Most of the pins of a microcontroller can be configured to be either digital inputs or output, and our program can either set their voltage level low (0V) or high (typically 3.3V or 5V) or read their voltage level (as digital LOW or HIGH). We will use this functionality, for example, to control LEDs that are connected to a digital output and to read the status of switches that are connected to a digital input. While digital I/O is extremely useful to transmit the state of a single bit, it is not a good interface for the transmission of a lot of data. For this task, slightly more complicated interfaces (often called buses) are used. A well-known example of a hardware interface for data transmission is the Universal Serial Bus (USB). This is a very powerful, flexible, but complicated-to-implement interface. It is usually not directly used in DIY robotics. The interfaces we use for our robots are simpler and easier to understand and use. Interfaces commonly used in Arduino robots include Universal Asynchronous Receiver/Transmitter (UART), Serial Peripheral Interface (SPI), the Inter-Integrated Circuit (I2C) bus, Pulse Width Modulation (PWM), and analog data transmission.

A microcontroller will have dedicated hardware for some or even all of these interfaces integrated on the same chip. That means the CPU does not need to spend time handling the transmission or reception of data (and we do not need to spend time implementing any of the algorithms for these interfaces). Our program will simply tell the CPU to pass data to these peripherals for transmission, or ask the peripheral for any received data. Easy access to these hardware interfaces is a major reason why microcontrollers are so great for DIY robotics. Most sensors, motor drivers, or any other component we might want to use in our robot will have one of these interfaces, and as long as we know how to program a microcontroller, we can easily talk to these components. More generally, access to these interfaces makes microcontrollers great for any kind of hardware hacking. Most chips that you find in appliances, toys, tools, printers, and game console controllers (everywhere, really) likely communicate over one of these interfaces. You can use a microcontroller to talk to them directly and gain lower-level access to their capabilities, rather than having to use the interfaces that the manufacturer exposes. An example of this (that works with very little hacking) is the popular use of the Nintendo Wii Nunchuck controller, a nice and inexpensive in-hand joystick, in DIY robotics projects. It uses the I2C interface.

Programming microcontrollers

Writing programs for microcontrollers is different from more typical programming on PCs. One of the main differences is that, in general, there is no operating system (OS) on a microcontroller. Your program is the only thing running on the CPU, and there is no OS to help manage resources or prevent the system from crashing. Your program also has direct access to hardware functionalities, such as sending power to any of the digital output pins. This is good in many ways: it makes it easy to understand what is going on during program execution, it means that there is almost no computational overhead from anything that is not your program, and it makes hardware access very transparent. However, it also means that we need to be a little more aware of what can go wrong if our program does not behave as intended since it is easy to make the program stall (for example, if we wait for a condition that never occurs), crash, or even damage attached hardware if we sent incorrect output signals. This direct access to hardware functionalities without the safeguards and layers of abstraction that an OS provides is why we sometimes call this type of programming hardware-near programming or, more commonly, embedded programming. Some languages lend themselves better to embedded programming than others. Most commonly, microcontrollers are programmed using the C language since it offers powerful and elegant ways to write highly efficient code that lets the programmers squeeze out every bit of performance, even from the smallest microcontroller. Even though C is sometimes regarded as a low-level language, is still much more user-friendly than going one level closer to machine language and programming in assembly.

The Arduino IDE supports not only C but also C++ (often abbreviated together as C/C++), and we rely on C++ to enable object-oriented programming (OOP), which allows us to easily use many third-party software libraries and make our own code reusable across different projects. We will take a much closer look at this in a later chapter. All examples in this book are written in C/C++.

The Arduino IDE does not support any other programming language, such as Python, for example. However, the Arduino project officially supports MicroPython, and you can use MicroPython and the OpenMV IDE to program Arduino boards using the popular Python programming language.

Pain points of working with microcontrollers

The lack of hardware abstraction provided by an OS means that the exact commands for doing a certain task (for example, setting a certain output pin high or sending data over a certain interface) can be very different from microcontroller to microcontroller, and you, the programmer, often have to dig through hundreds of pages of datasheets to understand how exactly to perform a certain operation, such as sending data over I2C on a new microcontroller. Even translating your final program to the machine code that can run on the microcontroller (compiling) can be complicated and extremely specific to the exact microcontroller you are using. And finally, transmitting the compiled program to the microcontroller often requires specialized hardware that can be complicated to use. For these reasons, the barriers to working with microcontrollers have traditionally been high, and they were mostly used by expert engineers rather than hobbyists, artists, students, or makers. To summarize, the traditional pain points preventing more people from using microcontrollers are as follows:

  • The fact that programs are highly hardware specific
  • The need for specialized compilers
  • The need for specialized hardware to transmit the compiled program

The creators of Arduino had the goal to get rid of these barriers and enable non-experts to use microcontrollers in their projects. Arduino is not the only project with this goal, but it has been the most successful, and it has had the largest impact on the maker scene by enabling many more people to take advantage of the power of microcontrollers.

What exactly is Arduino?

Arduino is a company that makes and distributes open source hardware and software. However, when we talk about an Arduino that controls a robot, we usually mean a circuit board with an Arduino-compatible microcontroller on it. But, as we already mentioned, Arduino is more than the physical hardware: it is an entire ecosystem of software, tools, and hardware that makes using microcontrollers accessible for anyone, with Arduino boards and the Arduino IDE at its center. Together, the IDE and the supported boards address the pain points we identified earlier. They simplify and streamline writing programs, compile them, and transmit the compiled programs to the board. There are also extension boards (called Arduino shields) that add additional functionality to standard Arduino boards without requiring specialized electronics skills.

There is a variety of different supported Arduino boards, and we will look at their differences and distinctions in more detail in a later chapter. One great aspect of Arduino is that the workflow of writing programs and transmitting them to the physical board is the same across all the different boards. In fact, in many cases, the exact same code can be used across different boards with different microcontrollers. No need to comb through datasheets for specific register names or to use specialized hardware for programming. When everything is set up, all you need to do is to connect your Arduino board to your computer with a standard USB cable, click one button, and the program will be compiled, transmitted, and starts running on your board automatically. For the remainder of this chapter, we will assume that our Arduino board is an Arduino Uno Rev3, but the steps to program it would not be different from any other official Arduino board that is supported by the IDE. Arduino boards also contain all the components needed to support the microcontroller and provide easy access to all of its pins. So, to answer the question in the title of this section: an Arduino microcontroller board is an easy-to-use circuit board with a microcontroller and all the electronics to support it, and can be programmed using the Arduino IDE.

Because of the popularity of Arduino, the fact that both hardware and software are open source, and the use of licenses that allow reusing the hardware design in commercial projects, a huge number of third-party projects that expand the Arduino ecosystem have emerged. There are numerous manufacturers of Arduino shields or entire (robot) starter kits, and even original equipment manufacturers (OEMs) of electronics components make development boards intended to be integrated into Arduino-based projects. There is also an incredible number of online tutorials, YouTube videos, and How-To guides that show you how to build a certain project with Arduino. As exciting as all of this is, experience shows that it can be overwhelming for anyone who is just entering the field of DIY electronics and robotics. And without a solid understanding of the basics, much of this content can feel more like noise rather than educational. The goal of this book is to equip you with a solid understanding of robotics with Arduino, the possibilities and limitations, as well as the pros and cons of many different design choices you have to make when building your own robot. After you have read this book, you will know where to start any Arduino robotics project that you want to build, and you will be able to understand and make use of the large amount of information and resources that are available from and for the Arduino robotics community.

 

The Arduino ecosystem

Let’s now take a look at the major components of both the Arduino IDE and the Arduino Uno board. After that, we will be ready to set everything up and write, transmit, and run our first Arduino program.

The Arduino IDE

The Arduino IDE is free and open source software available for Windows, macOS, and Linux systems. Arduino also offers a web-based version that works in your web browser and stores your files in the cloud as opposed to locally. The examples in this book assume that you are using a locally installed version of the IDE on a Windows computer, but most steps will be identical, or at least very similar, across the three systems. In September 2022, the Arduino IDE received a major upgrade from version 1.8 to version 2.0. Version 2.0 is easier to use and more powerful, which means that now is a better time than ever to start using Arduino!. Figure 1.3 shows how the Arduino IDE 2.0.3 looks on startup:

Figure 1.3 – The Arduino IDE right after launch

Figure 1.3 – The Arduino IDE right after launch

We will take a closer look at the Arduino IDE later in this chapter after we have set it up, but for now, let us understand what the key components and the purpose of this IDE are:

  • A text editor lets you write your C/C++ program right in the IDE. In Arduino parlance, programs are called sketches, a nod to the IDE’s origins in the Processing project (https://processing.org/). The editor has some useful features, such as syntax highlighting, auto-formatting, and auto-completion. However, it is a pretty simple editor still. While this simplicity is intentional, it is not as powerful as other modern code editors, such as Visual Studio Code, for example. There are more advanced alternatives to the built-in text editor, but for the purpose of this book, we will be using the IDE’s text editor as it is the most seamless option to develop Arduino programs.
  • A compiler lets you translate your code to machine language for the microcontroller you are using. Arduino makes using the compiler very easy; all it requires is one click on the checkmark button in the top-left corner. When the compiler runs, it produces some output in the console window that appears under the editor window. This output can be very useful for troubleshooting your program.
  • A programmer lets you seamlessly transfer the compiled machine code to your Arduino board that is connected to your PC via USB. All it takes is, again, one click on the arrow symbol in the top-left corner. And just like the compiler, the programmer will generate some output in the console under the editor that is useful for troubleshooting if the programming does not work as expected.
  • A debugger lets you run your code step by step on the Arduino’s microcontroller. This advanced feature can be very useful for finding problems that happen during program execution. However, the debugger only works with certain boards (not with the Arduino Uno) and may require additional hardware, depending on the board. If a compatible board is connected, the Play button with the little bug in the top-left corner of the Arduino IDE becomes available to start a debugging session.
  • A serial monitor lets you send text from the PC to the Arduino and can display text that your Arduino sends to the PC. This works with all boards and is an incredibly useful tool for debugging and interacting with your running program. The IDE also provides a serial plotter that can display multiple lines of numeric data sent from your Arduino board as a 2D live plot. The buttons to start the serial plotter and the serial monitor are located in the top-right corner of the IDE.
  • Built-in hardware abstraction libraries make your code more or less independent of the board you are working with. This feature is not really visible on the surface, but it might be the most important one. This is what allows you to program even complex Arduino boards without having to look at the datasheet of the microcontroller, and to use the exact same code that you developed for one board across many different Arduino boards.

Now that we have a good understanding of what the Arduino IDE is, let’s look at the other aspect of the Arduino ecosystem: one of the boards that can be programmed with the Arduino IDE.

The Arduino Uno

The Arduino Uno is the most widely used Arduino board due to its simplicity, ruggedness, and widespread availability. It is built around the ATmega328P microcontroller, which has a long history in low-cost DIY electronics projects. The Uno is a great board to get started with Arduino as it is low-cost and simple, yet it contains all the key functionalities of a microcontroller board and is very forgiving to wiring and other mistakes that might damage more complicated boards. Similar to what we did for the IDE, let us look at the key components of the board and what their functionalities are. We will go a little more into detail here since we will rely on a solid understanding of the board components in future chapters. Figure 1.4 shows the Arduino Uno R3 board for reference:

Figure 1.4 – The Arduino Uno Rev3 microcontroller board

Figure 1.4 – The Arduino Uno Rev3 microcontroller board

The key components that we will discuss next are labeled with numbers.

Main electronic components

The biggest chip on the board is the ATmega328P microcontroller (1). It is so big because it is enclosed in a socketed Dual Inline Package (DIP) housing, which allows you to replace it in case it gets damaged. This is the microcontroller that we will be programming toward the end of this chapter, and that controls all the output pins that you see lined along the bottom and top edges of the board. Let us call it the main microcontroller. It only needs very few peripheral components to run, namely the two small ceramic capacitors under and above it, and the little oscillator above it (under the R3 marking).

The second-largest chip on the board is another microcontroller, an ATmega16U2 microcontroller in a much smaller package that is soldered directly to the board (2). It comes pre-programmed with special firmware that lets it act as an interface between the USB connector and the ATmega328P. More technically, it implements a USB-to-serial converter. Let’s call this one the programmer. When we click the program button in the IDE, our computer starts communicating with this chip over USB, transmitting the compiled machine code to it. The programmer receives the code byte-by-byte over USB and transmits it to the main microcontroller over a serial interface. To enable this type of programming, there is a special bit of software already programmed into the main microcontroller, called the bootloader. We do not need to go into any more detail here about how the bootloader works. But it is worth mentioning that if you ever want to replace the main microcontroller, you need to either purchase one that is already pre-programmed with the Arduino bootloader or flash the Arduino bootloader onto it yourself.

There is a small RESET button in the top-left corner of the board (3). Pressing this button causes the main microcontroller to reset. It will stop the current program execution and start executing the program from the start, similar to rebooting a PC. The reboot of a microcontroller happens almost instantly. The reset button is typically not used very often, but it can be useful in the development process when you want to run your program from the start again to test something, or when the program has unexpectedly halted, and you need to reset it.

Below the reset button is the USB connector (4). On the Uno, this is a male USB Type-B port. Although this is a dated connector by now, it has the advantage of being very rugged and hard to damage. Smaller or third-party Arduino boards often have more modern Mini, Micro, or Type-C USB connectors.

Note

The Arduino can run on power provided by the USB port. However, if you use the Arduino’s 5V to power other consumers such as motors or long LED strips, you might exceed the 2.5 W of power that a USB port can provide. In this case, your PC will likely shut down the power to this port to protect itself from overcurrent. In the worst case though, damage to the PC’s USB port can occur.

The power connector for external power as well as the board’s power system is in the bottom-left corner (5). You can power the board through this connector with a voltage ranging from 7V to 12V, from a 2-cell lithium battery, for example. Directly above this connector is the linear voltage regulator that turns this input voltage into 5V, which is needed to run the microcontrollers. It is worth noting that this is not a very efficient kind of converter and can get hot quickly, depending on the power requirement of your project. In general, it is better practice to use a more efficient switched 5V regulator between the battery and your Arduino and connect its 5V output directly to the pin on your Arduino that is marked 5V. This way, you circumvent the onboard linear regulator altogether. We will investigate this and other power considerations in more detail in a later chapter.

There are 2 male 3x2 pin headers on the board. The one on the right (6) is labeled ICSP, which stands for In-Circuit Serial Programming. This is primarily a low-level programming port that can be used to flash the bootloader onto the main microcontroller. Beyond that, it can be used to access the SPI interface of the main microcontroller. The other male pin header is the ICSP interface for the programmer microcontroller (7). This is used to flash the USB-to-serial firmware onto the programmer during the production of the board. We will not need to use this interface.

There are two rows of female pin headers along the top and the bottom edge of the board. These pins are your Arduino’s interface to the world! This is where we connect all the physical components such as sensors, motor drivers, LEDs, displays, buttons, or potentiometers that we want to interact with. Very conveniently, the pins are all grouped by their function and labeled, making it easy for us to reference specific pins in our code (without having to look up anything in the datasheet of the microcontroller). Let us now look at the various groups of pins and their functions.

Power pins

As the name suggests, the POWER pins have to do with the power system of the board rather than with logical inputs and outputs. Going from left to right, they are as follows:

  • IOREF: This is a 5V pin that is meant to signal to specialized connected boards (called Arduino shields) what voltage the Arduino board is running on.
  • RESET: This pin is connected to the reset line of the microcontroller, which is internally pulled high by a large resistor. Connecting this pin to GND has the same effect as pressing the RESET button, effectively rebooting the main microcontroller.
  • 3.3V: This is an output pin that provides 3.3V from a very small internal linear regulator. It can be used to power small peripherals that require 3.3V, but it is again better practice to not rely on it but to use an external switched 3.3V regulator instead.
  • 5V: This pin connects directly to the 5V net of the board. It can be used to tap off 5V power for other components of your robot when the Uno is powered by the USB connector or the external power input. Or it can be used to power the Uno from a 5V source, such as an external 5V regulator.
  • GND: These pins provide access to the board reference potential (ground). In general, every component that we want to connect to our Arduino needs to share the same reference potential and must therefore be connected to the Arduino’s GND net. This is why the Uno has three GND pins. In practice, though, this is often not enough, and we will learn how we can use a solderless breadboard to get even better access to GND.
  • Vin: This pin is directly connected to the barrel connector in the bottom-left corner of the board. It can be used for the same purpose – to power the board from a battery or other voltage source in the range from 7V to 12V (with the caveat of relying on the inefficient onboard linear regulator).

On the left side of the top pin header is the AREF pin. It can be used to feed in an external reference voltage to Arduino Uno’s built-in analog-to-digital converter (ADC). By default, the ADC uses 5V as the voltage reference, which is acceptable for most applications, so the AREF pin is rarely used in practice.

GPIO pins

All other pins that are neither POWER pins nor AREF are General Purpose Input/Output (GPIO) pins and can be used as DIGITAL inputs and outputs. However, most pins of a microcontroller can be used for more than one functionality, depending on their configuration. To avoid confusion and simplify things a little, only pins 0 to 13 on the Arduino are labeled as DIGITAL. These digital pins can be used to either read digital input signals as HIGH or LOW (for example, from a push button), or to send a single bit of information (for example, to control a LED) by setting their output voltage to HIGH (5V) or LOW (GND). Some of the DIGITAL pins have a tilde in front of their pin number. This indicates that they can be used to send a PWM signal. This means we can ask them to automatically go HIGH and LOW repeatedly at a very high frequency, and we can easily control the width of the high pulse (from 0%, always LOW, to 100%, always HIGH). This capability is useful to control the brightness of LEDs, the speed of DC motors, or the position of RC servos, for example. Lastly, pins 0 and 1 are marked as RX and TX. This is because they are used by the serial interface between the main microcontroller and the programmer. The same interface is also used for any other communications with the IDE (for example, the serial monitor that we will look at later in this chapter). It is generally a good idea to try to avoid using these pins for anything else to avoid interference with these functionalities. If you need an additional serial interface for your application, you can use Arduino’s software serial to turn any two digital pins into an additional set of TX and RX pins.

The ANALOG IN pins can be used to read analog signals in the range of 0V to 5V. While digital inputs can only distinguish between two states (HIGH and LOW), the analog input pins can read voltages with a resolution of 10 bit, or 1,024 steps. This means they read a value of 0 when connected to GND, 512 when connected to 2.5V, and 1023 when connected to 5V, for example. A common use case for analog input pins is to read the output voltage of a potentiometer that can be used as a dial to set a continuous input value. These pins can alternatively be used as digital pins 14 through 19. Pins A4 and A5 are broken out twice on the Arduino board: once on the bottom right of the board and a second time, unlabeled, on the top left.

Beyond these basic functions (power, digital, and analog), many of the pins have alternative functions that can be selected via software. Let us get a quick overview of these additional functionalities here, even though we will take a much closer look (with examples) at how to use them in the later chapters. The Arduino IDE with its built-in hardware abstraction libraries makes configuring these special functionalities extremely easy:

  • The two analog pins A4 and A5 (and also the two unlabeled pins in the top-left corner) can be configured as the two pins for the I2C bus interface, namely SDA (pin A4) and SCL (pin A5).
  • Pins 11, 12, and 13 can be configured to be the three pins of the SPI interface, MOSI, MISO, and SCK, respectively. In this case, pin 10 can be used as a hardware-controlled chip select pin for the SPI bus, but any software-controlled digital pin can also serve this function.
  • Pins 2 and 3 can be configured as hardware interrupt triggers. This is a useful capability to react to changes in the voltage level on these pins (from LOW to HIGH or HIGH to LOW) with the shortest possible latency. Example applications for this include decoding the PWM signal from an RC receiver or counting the steps of an incremental motor encoder.

Our overview of the Arduino Uno is almost complete, but no microcontroller board is complete without a few indicator LEDs, and the Uno is no exception.

LEDs

The last major components to mention are the three yellow status LEDs and the green power LED on the board (8). Let us look at the three yellow status LEDs that are all arranged in a vertical line under pin 13, labeled L, TX, and RX:

  • The LED labeled L is connected to digital pin 13. It lights up when the pin is HIGH (5V), and it is off when the pin is LOW (GND). It is quite common to at least have one status LED on your robot to signal its current state. In the simplest case, you can let this LED constantly blink a heartbeat signal to show that the program is still running. When the LED is not blinking, you can immediately see that something unexpected has happened and that the program is stalled. Having this status LED built right into the board is very useful, and the very first program we will write in this chapter will not do much more than let this LED blink.
  • The two LEDs labeled TX and RX signal activity on the main microcontroller’s serial interface that is used to communicate with the programmer microcontroller and, by extension, with your PC. They are not directly connected to the digital pins 0 and 1 but are driven by the separate pins of the programmer. Whenever the main microcontroller is receiving data from the PC, the RX LED lights up, and whenever the main microcontroller sends data to the PC, the TX LED lights up. These LEDs are especially useful during the programming process to verify that the program is in fact transmitted from the PC to the board, in which case, both will blink rapidly for a brief period.

The green LED labeled ON is located on the right side of the board. When the board has good 5V power, this LED will be solidly on. It is useful for troubleshooting power issues with your project. If this LED starts flickering, shines less bright than usual, or even switches off altogether, you know that something is wrong with the power that is supplied to the board.

You now have a detailed understanding of the hardware components and functionalities of the Arduino Uno board. We will build on this knowledge in later chapters, where we look at many of these functionalities in more detail and introduce the code that is necessary to use them. In the next section of this chapter, we will set up the Arduino IDE on your PC and write our first program that will let the LED attached to pin 13 blink. We will also transmit a message over the serial port from the Arduino to the PC.

 

How to program your Arduino board

The main goal of the Arduino project is to make programming microcontrollers easy, and this section will walk you through the necessary steps. If this is your first time working with microcontrollers, you will hopefully enjoy the process. If you have experience in programming microcontrollers in more traditional ways with hardware-specific IDEs, ISP programmers, and a datasheet always on hand, you might be surprised by how much smoother the experience with the Arduino toolchain is. The whole process involves four steps, and we will go through each of them:

  • Installing the Arduino IDE on your system
  • Writing the program code in the IDE’s editor
  • Compiling the code for your Arduino board
  • Transmitting the compiled machine code to your Arduino board

Installing the Arduino IDE

To download the Arduino IDE, go to https://www.arduino.cc/en/software and select the download link for your operating system (Windows, Linux, and macOS are supported). Download the installer and follow the instructions for the full installation. The installation includes the hardware drivers that are necessary to enable the IDE to communicate with the Arduino boards via USB, so make sure to select the option to install the hardware drivers when prompted.

Once the IDE is installed successfully, you can open it, and it will look just as shown in Figure 1.3. The IDE has a simple and clear interface. Besides the buttons we already discussed, there are several drop-down menus accessible at the top and a few more shortcut buttons on the left. These include access to the Boards Manager and Library Manager, which we will talk about in more detail later.

You will notice that the IDE already shows some code in the editor when you first open it. This is a bare minimum, valid Arduino program (or sketch) that can be compiled and run on any Arduino board, but that does nothing at all.

You can see that every Arduino program or sketch consists of at least two functions: setup() and loop(). Just like the comments suggest, the setup function is executed only once right after the program starts. In it, we typically put all the code that configures the functionality of the pins and that initializes connected hardware, such as the sensors of our robot. After the setup function has been completed, the program will repeatedly execute the loop function as fast as it possibly can, until the Arduino is shut off or reset. Let us fill in these empty functions with a bit of code that actually does something! Even with only the Arduino Uno board and no additional hardware to interface with, we can still use the built-in LED on pin 13 and the serial interface to generate some interesting behavior and bring our Arduino board to life.

Writing your first Arduino program

To use the LED that is connected to pin 13, we must first configure pin 13 as a digital output pin. This will enable it to drive the LED. To do this, we need to add the following line of code to the setup function:

pinMode(13, OUTPUT);

This will tell the microcontroller on our Arduino board that we want to use this pin as an output, and not as input or as part of the SPI interface, for example. This line of code will work for our Arduino Uno where the LED is connected to pin 13. But it would not produce the intended effect on a different board type where the LED is connected to a different pin. We can instead write the following line, where we replaced the number 13 with the LED_BUILTIN macro:

pinMode(LED_BUILTIN, OUTPUT);

During compilation, LED_BUILTIN will be automatically replaced with the correct pin number for the board we are working with, which means that our program will work across many different boards. Similarly, OUTPUT will be replaced with the number 1.

To enable the serial interface such that we can send messages between the PC and the Arduino, we need to add the following line of code to the setup function:

Serial.begin(115200);

This line will start the serial interface at a baud rate of 115200 bps. The baud rate determines the data transmission speed of the serial interface. 115,200 bps will be our default serial baud rate for all examples in this book, as it allows for both reliable and fast communication. Directly after this line, we can start to use the serial interface. As is customary in programming tutorials, let us let our program print the words "Hello, world!" to the serial monitor. To do this, all we need to do is add the following line at the end of our setup function:

Serial.println("Hello, world!");

The Serial.println() functions will write the characters of the sentence "Hello, world!" one by one to the serial output. It will automatically add a line break at the end of it to make parsing and displaying this message easier. This is it for the setup function; there is nothing else we need to add.

In the loop function, we will periodically turn the LED on and off again, and also print out a corresponding message. To turn the LED on, we need to add the following line at the top of the loop function:

digitalWrite(LED_BUILTIN, HIGH);

This line sets the digital output of pin 13 to 5V, causing the LED to light up. Let’s also print a corresponding message and wait for half a second before we turn the LED off again with the following two lines:

Serial.println("LED on. ");
delay(500);

The delay function implements a busy wait and will halt the program execution for the specified number of milliseconds. It is usually good practice to avoid the use of delay() (or any other form of busy waiting in general) everywhere except in the setup function. The reason is that a busy wait prevents the CPU from doing anything useful during this time, which can cause many unintended consequences. We will introduce methods to avoid the use of delay in a later chapter, but for this first example, there is nothing wrong with using it. Lastly, let us turn the LED off again, print a notification, and wait another half a second before we automatically repeat the blink process all over again:

digitalWrite(LED_BUILTIN, LOW);
Serial.println("LED off.");
delay(500);

And this is all we need to do to write a program that lets the LED blink at a frequency of 1 Hz and outputs a little notification over the serial port every time it turns the LED on or off. Figure 1.5 shows how the final program looks in the Arduino IDE:

Figure 1.5 – The blink program with serial output statements

Figure 1.5 – The blink program with serial output statements

You might have noticed that this is not actually valid C++ code, since the main() function is missing. During the compilation process, this function will be automatically generated, and it calls the setup function once and then the loop function in an endless loop.

Compiling the code for your Arduino board

Now that you have written the code for your program, we need to translate it into machine code for the microcontroller on the Arduino Uno. To do this, you first need to tell the IDE what board you are using. Click the drop-down window in the center, click on Select other board and port and type the word uno in the search bar under BOARDS. Select the Arduino Uno entry. If your Arduino is connected to your PC, you can find and select the serial port on the right under PORTS. This step is needed to transmit the program to the board. Figure 1.6 shows where to select the board type and the serial port that you will be using for programming. When you are done, click OK:

Figure 1.6 – Selecting the board type and serial port

Figure 1.6 – Selecting the board type and serial port

Now, you can click on the checkmark symbol in the top-left corner to compile your program. As soon as you click on it, the console window (titled Output) will appear under the editor. The IDE will also display a pop-up message that says Compiling sketch…, and if all goes well, this message will change to Done compiling. A message in the black console window under the editor will inform you how much program storage space and dynamic memory are being used by your program. Figure 1.7 shows what the IDE looks like when compilation is successful:

Figure 1.7 – How the IDE looks after successful compilation

Figure 1.7 – How the IDE looks after successful compilation

The information in the console can be useful to keep an eye on for larger programs. If any of these values get close to 100%, the program can become unstable during execution. In this case, you will want to either optimize your program to use less storage and dynamic memory or upgrade to a more capable Arduino board that has more of them.

Transmitting the code to your Arduino board and running it

If everything is set up correctly, it is time to transmit your code to the Arduino! To start this process, click the arrow symbol in the top-left corner of the IDE. This will trigger the familiar compilation process, and as soon as the IDE is done compiling, it will start transferring the compiled machine code to the Arduino board via the USB-to-serial programmer interface. This should only take a short amount of time and is accompanied by two new pop-up messages: Uploading... and, if all goes well, Done uploading. If you look at the TX and RX LEDs on your Arduino board, you will see both blinking very rapidly during the transmission.

After the program is successfully transmitted, the Arduino board will immediately start running it. If all went well, you should see the status LED turn on and off at a frequency of 1 Hz. But we also put some serial print commands in our code. To see the content of these messages, we can use the serial monitor that is built into the Arduino IDE. In the IDE, click on the magnifier glass icon in the top-right corner to open the serial monitor. It will appear as a new tab under the editor area, next to the console. You will need to select the baud rate from the drop-down list in the right corner of the serial monitor that matches the one in the Serial.begin() command of our sketch – 115200 in our case. As soon as you set the correct baud rate, you should see alternating lines of "LED on." and "LED off." appear. And if you push the RESET button on your Arduino to start the program from the beginning, you will see the line "Hello, world!" appear once. This shows you that the setup function is indeed executed once at the beginning of the program. Figure 1.8 shows the output of the serial monitor, as well as the baud rate setting:

Figure 1.8 – Expected output in the serial monitor

Figure 1.8 – Expected output in the serial monitor

You will also see the TX LED flicker every time the status LED switches on or off. This is signaling that the Arduino is transmitting serial data, namely the messages ("LED on." and "LED off."). You can use the serial monitor to send a message to your Arduino board. To do this, type anything you like into the line at the top of the serial monitor and press Enter. This will send your text, character by character, to the Arduino board. The moment you press Enter, you will see the RX LED light up for a brief moment, indicating that data is in fact transmitted from the PC to the main microcontroller. We did not program our Arduino to react to serial data, so it will just ignore it and it has no effect on the execution of our program. But with a few minor changes to our program, we could control the frequency of the blinking with a message from the serial monitor, for example.

Congratulations, you have successfully written your first Arduino program and it is running right now on an Arduino Uno board on your desk! Now that everything is set up and working, you might want to play around with the program a little bit to get more familiar with the workflow. You can change the words that are being printed or the frequency of the blinking, or you can try to change the serial baud rate (both on the Arduino and on the PC side). You can also see what happens when there is an error in your program code – for example, when you delete a semicolon at the end of a line. In this case, the compiler will fail, but it will give you a useful error message and even highlight the area of code where the problem lies.

 

Examples of Arduino robot technology

Hopefully, you are excited about the fact that you are now able to program your Arduino microcontroller board. You can be sure that this is only the very beginning of our journey toward building real robots with our newly learned Arduino skills. Arduino technology is often used for research and development to quickly prototype hardware concepts, or even to build cost-effective production systems. Researchers and engineers use Arduino boards on every kind of robot, from solar-powered autonomous boats to monitor the water quality of lakes to scientific data collection on rockets and high-altitude balloons.

There are highly active open source software projects that let you turn your Arduino into a flight controller for autonomous airplanes (https://ardupilot.org/) or into the brains of your DIY 3D printer (https://marlinfw.org/). You just took the first step toward being able to do all these things yourself and become part of the active community of hobbyists, enthusiasts, researchers, and engineers who use Arduino for their robotics projects.

 

Summary

In this chapter, we have introduced the Arduino ecosystem with its two main components, the Arduino IDE and Arduino boards. We have taken an in-depth look at the versatile Arduino Uno and you have transferred your first program onto your own Arduino Uno, using the entire Arduino toolchain. We will build on all of this in the next chapter, where we will learn how to use the Uno’s interfaces to communicate with sensors, make motors spin, and control entire robots.

 

Further reading

The Arduino IDE and the Arduino Uno board are very well documented. Here are a few resources that can help you learn more about them:

About the Author
  • Lukas Kaul

    Lukas Kaul is a robotics Research Scientist, currently working at the Toyota Research Institute in Silicon Valley, where he develops mobile manipulation technologies to support people in their homes and in their workplace. Throughout his career he has worked on projects as diverse as humanoid robots, aerial robots and mobile manipulation systems. A maker at heart, Lukas has been using Arduino technology extensively for more than a decade in countless side-projects, ranging from mapping systems to self-balancing robots. Lukas is passionate about teaching robotics with Arduino to inspire and empower anyone who wants to enter the exciting field of robotics. He holds a PhD degree from the Karlsruhe Institute of Technology, Germany.

    Browse publications by this author
Practical Arduino Robotics
Unlock this book and the full library FREE for 7 days
Start now