Chapter 1

Setting Up the Tools
Integrated Circuit, Computer, Technology
Unlike other programming languages and their environments, Arduino is focused on allowing users who are not experienced in software and electronics programming to work on highly technical projects. Usually, such projects involve creating digital music instruments, working in robotics, games, and much more. The reason why the Arduino environment is preferred for fields such as mechatronics, robotics, electrical engineering, and even for those who are just tech enthusiasts is that users don’t need to be above-average regarding the software of their project and the electronic design as well. This makes even beginners exploring the world of technology and computing highly motivated when they find that Arduino allows them to transform their creative ideas into a tangible reality.
Due to the incredible functionality and usability of the Arduino environment, educational institutions worldwide use it for professionally training their students in their respective majors. For instance, people who are committed to creating designs and sketches of a product’s prototype will absolutely need to be aware of the product's technicalities before they can even proceed. However, with Arduino, this extra layer of complexity is shaved off from their work. They can easily focus on the design without having to worry about the sophistication under the hood of the product. In other words, Arduino itself is designed by people who are not specialists in robotics, electronics, or even engineering; this is why they have kept the end-user as their primary focus and have given the best user-friendly experience to help facilitate the user.
Although Arduino's hardware capabilities are what makes it stand out, the reality is that without the proper software, the hardware is just a useless chunk of metal. Hence, Arduino collectively refers to both the software and hardware aspects of the environment.
The Arduino Software
Like any computer hardware, unless there’s software that is controlling it, it's nothing more than a useless pile of metal. The software allows a user to directly interact with a system’s embedded hardware, in turn utilizing its functionalities for specific purposes. This also applies to Arduino hardware as well. Since Arduino is used for specialized projects, the software needs to be tailored accordingly as well. These programs designed and developed specifically for Arduino hardware are known as ‘sketches .’ Just as an application is developed using the IDE of a particular programming language, sketches are also created using the Arduino IDE.
Arduino Hardware
The piece of hardware that the user will end up interacting with is the ‘Arduino board .’ The software that we created using the Arduino IDE directly interacts with this board, executing any instructions embedded within the program. Generally, people do not use just the Arduino board itself; on the contrary, there are extra components available that pop onto the Arduino board extending its usability. For instance, we can attach things like switches, thermal-sensors, gyroscopes, pressure sensors, LEDs, output displays, and even motors to the Arduino board, all depending on what the project requires.
When using the Arduino environment for a project, users can choose from a variety of Arduino hardware boards according to the needs of the project and the Arduino software. There are a variety of Arduino boards available in the community for users to pick up. There are official Arduino boards released by the Arduino team, as well as Arduino boards that are released by the members of the community. Suppose you are picking up a project from the community and modifying it according to your needs. In that case, it's recommended to use the tools as specified by the original project designer or swap a few things in and out as you see fit. Arduino boards come in a variety of form-factors. You can find boards that are as small as credit cards and boards that are just large enough to design a project that features applications such as wearables. However, one thing to note is that different sized boards do not have the same specifications. Generally, smaller Arduino boards have fewer connection points for external peripherals and an underwhelming processor. In contrast, bigger boards feature a more robust processor and an increased number of connections (since the size is bigger, it can easily accommodate more ports). A quick run-through of the popular Arduino boards has been given below;
Setting Up The Arduino IDE
The Integrated Development Environment software for Arduino is available for the three most popular Operating Systems, i.e., Windows, macOS, and Linux. To download the IDE, you will have to visit Arduino’s official website to do so, which has also been linked below;
http://arduino.cc/en/Main/Software
When you visit the website, select the Operating System for which you want to download the IDE application, and then follow the instructions. Once the Arduino IDE is installed, we can launch it by simply clicking on the ‘Arduino.exe ’ file. However, installing the IDE is not enough because, at this point, the software (the IDE) and the hardware (the Arduino board) are not able to interact with each other. This is because we have not installed the necessary drivers for the Arduino board we are using. Luckily, this step is nothing complicated as well.
If you are using a PC running on Windows, connect the Arduino board to the computer using a USB cable. Once the board is connected, Windows will automatically find and install the necessary drivers. If the PC is unable to install the drivers properly for some reason, we can manually do this in the device manager. The IDE installation folder also has a separate sub-folder for drivers of Arduino boards. There’s a good chance that the driver for the board you are using will be in this folder as well. So open the device manager, look for the ‘unrecognized’ drivers, and then right-click them to open their properties. After this, all you need to do is simply click ‘update driver’ and choose the manual option and then specify the file directory which contains the drivers. In this way, you manually install your Arduino board’s drivers.
On a Mac, the IDE application installer file will be a disk image, and inside this disk image, there is also an installation wizard for the drivers as well. This file is generally named ‘FTDIUSBSerialDriver.’ Once you install the IDE, then simply run this file to install the drivers as well.
The Arduino Board
In this section, we will talk about the proper way in which we can set up an Arduino board and see if it works correctly. Most of the available boards feature a small LED that lights up when connected to a power source. Check for the USB port on your Arduino board and then connect it to your PC via a USB cable. If the LED on the board lights up, it indicates that the board is working properly (powering up at least). There is another LED indicator on the board as well that can be found in the middle area. This LED lights up with an orange color and flickers to show there is no issue with the components.
Upon connecting the board to your PC, if the green LED does not light up, it means that the board has a power issue. There’s a possibility that the USB port is faulty or the cable itself; however, if the peripherals are working, you should plug in the power adapter. If the LED still does not light up, then the problem is in the board’s power supply. It’s better to get a new one or a replacement in such cases.
The flashing orange LED light is controlled by a simple program loaded onto the board by the manufacturers themselves. If the orange LED light does not flicker, it means that either the sketch program has not been loaded on to the board’s chip or is faulty. In such cases, you should manually flash the sketch program on the board. If it still doesn’t work after doing that, then there’s a problem with the Arduino board.
Using the Arduino’s Integrated Development Environment
This section will be going over creating an Arduino sketch and then using it on the board.
Once we launch the IDE we downloaded on to our PC, we now can generate sketches, launch existing sketches, and even modify the sketches we have access to. These actions can be performed using the buttons present in the IDE’s toolbar or by using assigned short-cut keys. However, we will not go into any further details of how to use the IDE’s interface.
In the Arduino IDE, examples are also available to show the code for performing basic tasks on the Arduino board. To access these demonstrative sketches, you will have to go to the IDE toolbar and find the ‘Files’ option. In the ‘Files’ drop-down menu, go to ‘Examples,’ and  you will find the examples section with a range of basic sketches for the Arduino board. For instance, the code for controlling the board’s LED blinking can be found within this section as the ‘Blink ’ sketch. It is easier for someone who does not have much experience with programming and coding to use sketch perfectly well because of these example codes. Apart from the basic codes, 17 example codes cover all the board's functionalities that can be controlled through sketch programs. Users can simply import the example code for the task they wish the board to execute and easily complete their projects. This convenience is very appreciated within the programming and professional community like mechatronics as well.
Once we have created a sketch we want to use on the Arduino board, we must compile it first. The board cannot use the sketch program unless it has been compiled before-hand. Once the sketch program has finished compiling, the user will see the ‘Done Compiling ’ message in the IDE’s console. However, one should always be wary of the sketch’s size before using it with the board. This is because Arduino has limited storage support for the sketches being imported. If the sketch program exceeds the board’s size limit, then the board's code execution will simply fail. Once you compile the sketch program, the sketch's size will be displayed in the IDE’s console along with the size limit supported by the board itself. Different boards have different size limits, so check the maximum limit of the Arduino board you are using. An example of such a message has been shown below;
Binary sketch size: 1008 bytes (of a 32256 byte maximum)
If the instructions detailed in the sketch program exceeds the size that is supported by the Arduino board you are using, then the IDE will display the following error message;
Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size
for tips on reducing it.
If you encounter this error, you will have to shave down the sketch program to decrease its size until it can be accommodated within the board’s memory. If making changes to the sketch program is not an option, then the only alternative is to simply get an Arduino board with larger memory space.
Like the Python and C programming language IDEs, the Arduino IDE compiler can also display errors made in the code of the sketch program. All the errors can be seen in the console after the compilation. However, once users import an example code and modify it by themselves, the IDE does not allow them to save these changes to the example file itself. This is to ensure that the integrity of the example codes remains intact. Once you use an example code and modify it, you will have to save it using the ‘Save As ’ option, which can be found in the toolbar's ‘Files’ menu. Suppose you know that you’ll frequently be making modifications and tweaking the source code. In that case, it is recommended to specify the sketch program's iteration to keep track of which changes were made to which iteration of the same sketch.  Another important thing to be mindful of is that once a sketch program is uploaded to the Arduino board, then it cannot be downloaded back to the system from where it was originally exported. That’s why you should always save your sketch programs on the system before uploading it to the board.
Exporting the Sketch Program and Executing it on an Arduino Board
This section will discuss how to export the sketch program we created and saved on our system to the Arduino board and see the code work its magic.
First and foremost, to copy the sketch from our system to the Arduino board, both need to be connected. So, we need a USB cable that has A-type connection points on both ends. We then connect one end to the Arduino board and the second end to our system. Once the connection has been established, we are ready to export the sketch file to the board.  Before we can do that, we must run the Arduino IDE and load a sketch program on to it. To keep things simple, we will export the blink sketch, which is available in the examples section in the IDE, to the connected Arduino board.
Once the IDE has loaded the sketch program we want to export, the next thing to do is to go to the IDE’s toolbar and click the ‘Tools ’ menu. From the drop-down list, look for the ‘Boards ’ option. The Arduino board that is connected to your system will show up here; at this point, all you have to do is look for the name of the board you are using and select it. Once this is done, go to the ‘Tools ’ menu again and this time, look for the ‘Serial Port ’ option. Over here, you will find all the serial ports that are present on the system you are using. If your system is running the Windows OS, then you will either find a single entry or multiple entries in this section. In case you see only a single entry, then that’s the port on which your board is connected to your system. If there are multiple entries, then the board will most likely be the last entry. In case you are using a Mac, then each entry shown in the ‘Serial Port ’ option will have two iterations, and each iteration will have different ending values. Selecting either entry is fine.
Once you have selected the board and the corresponding serial port, all that’s left to do is select the upload button on the main IDE interface or go to the ‘Files ’ menu in the toolbar and select the ‘Upload to I/O board ’ option from there.
Once these steps have been performed, the IDE will automatically compile the code in the sketch program. When the compilation is done, the program will be exported to the Arduino board. Once the export process is completed, the board will immediately start executing the instructions detailed in the sketch program exported to it. In this case, two LEDs will start blinking on the Arduino board as specified by the program. Once the sketch program's instruction set is completely executed, the LED's blinking will stop and the LED will be reset to its original state.
This is necessary because the PC needs to know which board the code needs to be sent to and which port connects it to the PC. Once the export process begins, the sketch currently being executed on the Arduino board is suspended and until the new sketch program is loaded on to it. Once the process is completed, the execution of the new sketch begins. However, a thing to keep in mind is that whenever a sketch program is exported to an Arduino board, the sketch program running currently on the board is overwritten and lost. So, it is recommended to save all the sketches that you create because you might need it in the future.
There are some cases where the upload process might not be successful. Usually, the reason for this is that some old Arduino boards and some new versions have compatibility issues. In such scenarios, the IDE will display an error message to the user when the sketch program's export is unsuccessful. Most of the time, if you encounter this error, the issue is caused by an incorrect selection of the Arduino board or the serial port. Another case could be that the board is simply just not connected properly to the system. Selecting the wrong port is one of the most common causes of this issue. An easy workaround to this is to disconnect the Arduino board connected to the system and then check the ports being shown in the IDE's serial ports menu. Once you have taken a look at the available serial ports, connect the board back to the system and then check one which was not shown previously. The new port being displayed is the one through which your board is connected to the system.
Building a Sketch Program and Saving it
In this section, we will discuss the process of using the Arduino IDE to create a sketch program and then save it onto your system.
Just as how we can open Microsoft Word and choose the ‘New ’ option to create an empty file and then fill it with content, in the same way, we can create a new sketch program by simply opening the IDE and choosing the ‘New ’ option under the ‘Files ’ menu. Once this is done, a new tab will be opened within the IDE to isolate the program you are working on from other sketches. In this tab, you can write as many code lines as necessary for your project (keeping in mind the size limit, obviously). Here’s an example of a modified ‘blink ’ code available in the IDE. The difference over here is that the duration in which the light stays illuminated before blinking is doubled.
const int ledPin = 13; // LED connected to digital pin 13
void setup()
{
pinMode(ledPin, OUTPUT);
}
void loop()
{
digitalWrite(ledPin, HIGH); // set the LED on
delay(2000); // wait for two seconds
digitalWrite(ledPin, LOW); // set the LED off
delay(2000); // wait for two seconds
}
If we are using this code as a sketch program, we will have to compile it. So let’s go over the process of exporting code on to Arduino boards. First, we will write this code (or copy it if you want to) in the IDE, and then we will compile it using the ‘Compile ’ option in the IDE interface and export it to the board using the ‘Upload ’ option either through the ‘Files ’ menu or through the interface button. Once the file is uploaded, we then save it on our system as we might need it in the future. To do this, we use the ‘Save ’ or ‘Save As ’ option in the ‘Files ’ menu.
When you save a sketch program, by default, the IDE software will set the location to a directory named ‘Arduino ’ in the user’s ‘My Documents .’ This happens when we are using a Windows system; if it’s a Mac, then the default file directory will be inside the ‘Documents ’ folder. It is recommended to name your sketch programs such that they reflect their usage or the instructions; however, the name of the sketch cannot be the same as the example sketch files. This makes it easier when you are dealing with a lot of sketch programs and saves you from the trouble of having to look through each program and see what it does before you find the sketch you’re looking for. Using the default save location of the IDE has its perks as well. Sketch program files stored in this directory are automatically displayed within the ‘Sketchbook menu ’ of the IDE, making it quicker and easier for the user to access.
One of the weaknesses of the Arduino IDE is its absence of sketch version management. This means that the IDE application does not have the functionality to revert the modifications made to a sketch over different iterations. So, if you find yourself frequently modifying your sketch files, then it is recommended that you keep each modified version of the program saved on your system. In this way, if you wish to use an older version of the same sketch program, you can do so.
If you are creating an Arduino IDE program from scratch or extending the example sketches, then it’s a good idea to compile the program frequently. In this way, you can easily fix any errors that pop up as you finalize the code without having to deal with a whole bunch of errors at the end and getting overwhelmed with the necessary changes.
Before we move on, there’s one final thing that needs to be discussed and it is the folder that contains the sketch file itself. In the Arduino IDE, the sketch programs must be stored within a folder that has a name matching the program's name.
Working with Arduino
Before we conclude this chapter, we will briefly demonstrate building a simple Arduino project using an Arduino board, some electrical components, and the Arduino IDE. This section will be brief and concise as practical projects have been discussed in detail in this book's upcoming chapters.
In this demonstration, we will be looking at a project which involves an LDR sensor connected to the Arduino board. This sensor will be responsible for controlling the frequency at which the LED on the board blinks and the duration as well. Since the core functionality is still the blinking of LED, we will be using the ‘blink’ sketch example and modify it according to the project's needs.
The idea here is that the LDR sensor will react to the board’s LED illumination intensity. The LDR sensor will be connected to ‘Pin 0’ on the analog circuit and the board LED is accessed through ‘pin 13’ on the digital section. Now that the project has been set up, all that’s left to do is create a sketch program and then export it to the Arduino board connected to our system. The sketch which will be used is as follows;
const int ledPin = 13; // LED connected to digital pin 13
const int sensorPin = 0; // connect sensor to analog input 0
void setup()
{
pinMode(ledPin, OUTPUT); // enable output on the led pin
}
void loop()
{
int rate = analogRead(sensorPin); // read the analog input
Serial.println(rate);
rate = map(rate, 200,800,minDuration, maxDuration); // convert to blink rate
digitalWrite(ledPin, HIGH); // set the LED on
delay(rate); // wait duration dependent on light level
digitalWrite(ledPin, LOW); // set the LED off
delay(rate);
}
Before we can even leverage the sensor's functionality, it needs to be connected to the board so the two components can communicate with each other. To do this, we will have to create a simple circuit that will consist of the LDR sensor itself and a suitable resistor. A resistor with a rating between 1000 to 10,000 ohm will be work just fine. Now that we know how the components need to be connected, let’s discuss the program demonstrated above. The core concept around which this program is designed is to define a certain value which corresponds to the intensity of the LED light. The brightness of the light emitted by the LED at pin ‘0’ will be interpreted by the LDR sensor connected to the board and its value will change accordingly. Based on this changing value, the sensor will increase or decrease the corresponding LED's voltage level accordingly. To read the value being pushed out by the sensor, we use a function known as ‘analogRead() .’ So, if the sensor detects that the light’s brightness is high, then the value will also be read as high by the function (in this case, the value will be ‘800’). Similarly, if the light's brightness is low, then the value given will be low as well (in this case, ‘200’). The voltage of the LED will be controlled by the LDR sensor accordingly.
We can specify the flickering rate of the LED by using the ‘map()’ function as well. The following code shown below demonstrates this;
const int ledPin = 13; // LED connected to digital pin 13
const int sensorPin = 0; // connect sensor to analog input 0
// the next two lines set the min and max delay between blinks
const int minDuration = 100; // minimum wait between blinks
const int maxDuration = 1000; // maximum wait between blinks
void setup()
{
pinMode(ledPin, OUTPUT); // enable output on the led pin
}
void loop()
{
int rate = analogRead(sensorPin); // read the analog input
// the next line scales the blink rate between the min and max values
rate = map(rate, 200,800,minDuration, maxDuration); // convert to blink rate
digitalWrite(ledPin, HIGH); // set the LED on
delay(rate); // wait duration dependent on light level
digitalWrite(ledPin, LOW); // set the LED off
delay(rate);
}
We can also use the Serial Monitor available in Arduino to take a look at various stuff to fine-tune the sketch program. For instance, we can observe the frequency at which the LED blinks at certain variable values. So, we can precisely know the blinking rate at a specific value and then set the value at which we want it to blink. This frequency is displayed in the IDE’s Serial Monitor. The following lines of code demonstrate the usage of Serial Monitors;
const int ledPin = 13; // LED connected to digital pin 13
const int sensorPin = 0; // connect sensor to analog input 0
// the next two lines set the min and max delay between blinks
const int minDuration = 100; // minimum wait between blinks
const int maxDuration = 1000; // maximum wait between blinks
void setup()
{
pinMode(ledPin, OUTPUT); // enable output on the led pin
Serial.begin(9600); // initialize Serial
}
void loop()
{
int rate = analogRead(sensorPin); // read the analog input
// the next line scales the blink rate between the min and max values
rate = map(rate, 200,800,minDuration, maxDuration); // convert to blink rate
Serial.println(rate); // print rate to serial monitor
digitalWrite(ledPin, HIGH); // set the LED on
delay(rate); // wait duration dependent on light level
digitalWrite(ledPin, LOW); // set the LED off
delay(rate);
}
The LDR can also be used for purposes other than simply controlling the LED blink rate. For instance, we can wire a small speaker to ‘pin 9’ and its resistor to ground on the digital connection pins to manipulate the resulting sound’s volume.
Since we are working with sound this time, we will have to adjust the frequency at which the pin turns on and off such that it matches with a frequency in the sound spectrum. To do this, we can simply define a variable as ‘rate ’ and then divide it by a factor of 100. The following lines of code demonstrate this:
const int ledPin = 13; // LED connected to digital pin 13
const int sensorPin = 0; // connect sensor to analog input 0
const int minDuration = 100; // minimum wait between blinks
const int maxDuration = 1000; // maximum wait between blinks
void setup()
{
pinMode(ledPin, OUTPUT); // enable output on the led pin
}
void loop()
{
int sensorReading = analogRead(sensorPin); // read the analog input
int rate = map(sensorReading, 200,800,minDuration, maxDuration);
rate = rate / 100; // add this line for audio frequency
digitalWrite(ledPin, HIGH); // set the LED on
delay(rate); // wait duration dependent on light level
digitalWrite(ledPin, LOW); // set the LED off
delay(rate);
}