Arduino Tutorial
Arduino Tutorial
Arduino is a project, open-source hardware, and software platform used to design and build electronic devices. It
designs and manufactures microcontroller kits and single-board interfaces for building electronics projects.
The Arduino boards were initially created to help the students with the non-technical background.
The Arduino board consists of sets of analog and digital I/O (Input / Output) pins, which are further interfaced
to breadboard, expansion boards, and other circuits. Such boards feature the model, Universal Serial Bus (USB),
and serial communication interfaces, which are used for loading programs from the computers.
It also provides an IDE (Integrated Development Environment) project, which is based on the Processing Language to
upload the code to the physical board.
The projects are authorized under the GPL and LGPL. The GPL is named as GNU General Public License. The
licensed LGPL is named as GNU Lesser General Public License. It allows the use of Arduino boards, it's software
distribution, and can be manufactured by anyone.
o Finger button
o Light as a sensors
o LED button
o Designing
What is Arduino?
Arduino is a software as well as hardware platform that helps in making electronic projects. It is an open source
platform and has a variety of controllers and microprocessors. There are various types of Arduino boards used for
various purposes.
The Arduino is a single circuit board, which consists of different interfaces or parts. The board consists of the set of
digital and analog pins that are used to connect various devices and components, which we want to use for the
functioning of the electronic devices.
Most of the Arduino consists of 14 digital I/O pins.
The analog pins in Arduino are mostly useful for fine-grained control. The pins in the Arduino board are arranged in a
specific pattern. The other devices on the Arduino board are USB port, small components (voltage regulator or
oscillator), microcontroller, power connector, etc.
Features
o Arduino programming is a simplified version of C++, which makes the learning process easy.
o The Arduino IDE is used to control the functions of boards. It further sends the set of specifications to the
microcontroller.
o Arduino does not need an extra board or piece to load new code.
History
The project began in the Interaction Design Institute in Ivrea, Italy. Under the supervision of Casey Reas and Massimo
Banzi, the Hernando Bar in 2003 created the Wiring (a development platform). It was considered as the master thesis
project at IDII. The Wiring platform includes the PCB (Printed Circuit Board). The PCB is operated with the ATmega168
Microcontroller.
The ATmega168 Microcontroller was an IDE. It was based on the library and processing functions, which are used to
easily program the microcontroller.
In 2005, Massimo Banzi, David Cuartielles, David Mellis, and another IDII student supported the ATmega168 to the
Wiring platform. They further named the project as Arduino.
The project of Arduino was started in 2005 for students in Ivrea, Italy. It aimed to provide an easy and low-cost
method for hobbyists and professionals to interact with the environment using the actuators and the sensors. The
beginner devices were simple motion detectors, robots, and thermostats.
In mid-2011, the estimated production of Arduino commercially was 300,000. In 2013, the Arduino boards in use
were about 700,000.
Around April 2017, Massimo Banzi introduced the foundation of Arduino as the "new beginning for Arduino". In July
2017, Musto continued to pull many Open Source licenses and the code from the websites of the Arduino. In October
2017, Arduino introduced its collaboration with the ARM Holdings. The Arduino continues to work with architectures
and technology vendors.
Microcontroller
The most essential part of the Arduino is the Microcontroller, which is shown below:
o Microcontroller is small and low power computer. Most of the microcontrollers have a RAM (Random Access
Memory), CPU (Central Processing Unit), and a memory storage like other computer systems.
o It has very small memory of 2KB (two Kilobytes). Due to less memory, some microcontrollers are capable of
running only one program at a time.
o It is a single chip that includes memory, Input/Output (I/O) peripherals, and a processor.
o The GPIO (General Purpose Input Output) pins present on the chip help us to control other electronics or
circuitry from the program.
We have many electronic devices around us. Most of the appliance consists of the microcontroller for its functioning.
Let's discuss some of the examples.
o Microcontroller present in Microwave Oven accepts the user input and controls the magnet run that
generate microwave rays to cook the food and displays the output timer.
o Modern cars also contain dozens of microcontrollers working in tandem (one after another) to control
functions like lighting, radio interface, etc.
Projects
We need a software to install our sketch or code to the Arduino board. The LED will blink after the successful
uploading of code. The software is called as Arduino IDE (Integrated Development Environment).
There are various projects created with the help of the Arduino. Some of the projects are listed below:
Some projects require a list of components. So, for easy convenience and hands-on projects, the Arduino kits are
available easily in market.
Arduino Kits
We can easily start with our electronics projects using the complete kit. It also helps us to create hand-on and
engaging projects.
Arduino IDE
The IDE makes the traditional projects even easier and simpler. The USB cable is used to load the program or sketch
on the specific Arduino board.
The IDE application is suitable for Windows, Mac OS X, and Linux. It supports the programming language C and C++.
We need to connect the Genuino and Arduino board with the IDE to upload the sketch written in the Arduino IDE
software.
Many other companies including Sparkfun Electronics, also make their own boards that are compatible with Arduino
IDE.
Arduino Boards
There are variety of Arduino board used for different purposes. The board varies in I/O pins, size, etc. The various
components present on the Arduino boards are Microcontroller, Digital Input/Output pins, USB Interface and
Connector, Analog Pins, Reset Button, Power button, LED's, Crystal Oscillator, and Voltage Regulator. Some
components may differ depending on the type of board.
o Arduino UNO
o Arduino Nano
o Arduino Mega
o Arduino Due
o Arduino Bluetooth
Shields
o Shields are defined as the hardware device that can be mounted over the board to increase the capabilities
of the projects.
o The shield is shown below:
o The shield together with Arduino can make the projects even smarter and simpler. For example, Ethernet
shields are used to connect the Arduino board to the Internet.
o The shields can be easily attached and detached from the Arduino board. It does not require any complex
wiring.
Prerequisite
The requirement to learn Arduino is the basic knowledge of C and C++ programming language. A basic understanding
of circuits, Microcontrollers, and Electronics is also essential.
Arduino IDE
The Arduino IDE is an open-source software, which is used to write and upload code to the Arduino boards. The IDE
application is suitable for different operating systems such as Windows, Mac OS X, and Linux. It supports the
programming languages C and C++. Here, IDE stands for Integrated Development Environment.
The program or code written in the Arduino IDE is often called as sketching. We need to connect the Genuino and
Arduino board with the IDE to upload the sketch written in the Arduino IDE software. The sketch is saved with the
extension '.ino.'
Toolbar Button
The icons displayed on the toolbar are New, Open, Save, Upload, and Verify.
It is shown below:
Upload
The Upload button compiles and runs our code written on the screen. It further uploads the code to the connected
board. Before uploading the sketch, we need to make sure that the correct board and ports are selected.
We also need a USB connection to connect the board and the computer. Once all the above measures are done, click
on the Upload button present on the toolbar.
The latest Arduino boards can be reset automatically before beginning with Upload. In the older boards, we need to
press the Reset button present on it. As soon as the uploading is done successfully, we can notice the blink of the Tx
and Rx LED.
If the uploading is failed, it will display the message in the error window.
We do not require any additional hardware to upload our sketch using the Arduino Bootloader. A Bootloader is
defined as a small program, which is loaded in the microcontroller present on the board. The LED will blink on PIN 13.
Open
The Open button is used to open the already created file. The selected file will be opened in the current window.
Save
New
Verify
The Verify button is used to check the compilation error of the sketch or the written code.
Serial Monitor
The serial monitor button is present on the right corner of the toolbar. It opens the serial monitor.
It is shown below:
When we connect the serial monitor, the board will reset on the operating system Windows, Linux, and Mac OS X. If
we want to process the control characters in our sketch, we need to use an external terminal program. The terminal
program should be connected to the COM port, which will be assigned when we connect the board to the computer.
Menu Bar
o File
When we click on the File button on the Menu bar, a drop-down list will appear. It is shown below:
Let's discuss each option in detail.
New
The New button opens the new window. It does not remove the sketch which is already present.
Open
It allows opening the sketch, which can be browsed from the folders and computer drivers.
Open Recent
The Open Recent button contains the list of the recent sketches.
Sketchbook
It stores the current sketches created in the Arduino IDE software. It opens the selected sketch or code in a new
editor at an instance.
Examples
It shows the different examples of small projects for a better understanding of the IDE and the board. The IDE
provides examples of self-practice.
Close
The Close button closes the window from which the button is clicked.
Save
The save button is used to save the current sketch. It also saves the changes made to the current sketch. If we have
not specified the name of the file, it will open the 'Save As...' window.
Save As...
We can save the sketch with a different name using the 'Save As...' button. We can also change the name accordingly.
Page Setup
It allows setting the page margins, orientation, and size for printing. The 'Page Setup' window will appear as:
According to the settings specified in the 'Page Setup', it prepares the current sketch for printing.
Preferences
Quit
The Quit button is used to close all the IDE windows. The same closed sketch will be reopened when we will open the
Arduino IDE.
o Edit
When we click on the Edit button on the Menu bar, a drop-down list appears. It is shown below:
Let's discuss each option in detail.
Undo
The Undo button is used to reverse the last modification done to the sketch while editing.
Redo
The Redo button is used to repeat the last modification done to the sketch while editing.
Cut
It allows us to remove the selected text from the written code. The text is further placed to the clipboard. We can
also paste that text anywhere in our sketch.
Copy
It creates a duplicate copy of the selected text. The text is further placed on the clipboard.
The 'Copy for Forum' button is used to copy the selected text to the clipboard, which is also suitable for posting to
the forum.
Copy as HTML
The 'Copy for Forum' button is used to copy the selected text as HTML to the clipboard. It is desirable for embedding
in web pages.
Paste
The Paste button is used to paste the selected text of the clipboard to the specified position of the cursor.
Select All
Go to line...
Comment/Decomment
The Comment/ Decomment button is used to put or remove the comment mark (//) at the beginning of the specified
line.
Increase Indent
It is used to add the space at the starting of the specified line. The spacing moves the text towards the right.
Decrease Indent
It is used to subtract or remove the space at the starting of the specified line. The spacing moves the text towards the
left.
Find...
It is used to find the specified text. We can also replace the text. It highlights the text in the sketch.
Find Next
It highlights the next word, which has specified in the 'Find...' window. If there is no such word, it will not show any
highlighted text.
Find Previous
It highlights the previous word, which has specified in the 'Find...' window. If there is no such word, it will not show
any highlighted text.
o Sketch
When we click on the Sketch button on the Menu bar, a drop-down list appears. It is shown below:
Verify/Compile
It will check for the errors in the code while compiling. The memory in the console area is also reported by the IDE.
Upload
The Upload button is used to configure the code to the specified board through the port.
It is used to override the Bootloader that is present on the board. We can utilize the full capacity of the Flash
memory using the 'Upload Using Programmer' option. To implement this, we need to restore the Bootloader using
the Tools-> Burn Bootloader option to upload it to the USB serial port.
It allows saving a .hex file and can be kept archived. Using other tools, .hex file can also be sent to the board.
Include Library
Include Library includes various Arduino libraries. The libraries are inserted into our code at the beginning of the
code starting with the #. We can also import the libraries from .zip file.
Add File...
The Add File... button is used to add the created file in a new tab on the existing file.
For example, let's add 'Blink' file to the 'Javatpoint' file. The tab will now appear as:
We can also delete the corresponding file from the tab by clicking on the small triangle -> Delete option.
Tools
When we click on the Tools button on the Menu bar, a drop-down list appears. It is shown below:
Auto Format
The Auto Format button is used to format the written code. For example, lining the open and closed curly brackets in
the code.
Archive Sketch
The copy of the current sketch or code is archived in the .zip format. The directory of the archived is same as the
sketch.
This button is used to fix the inconsistency between the operating system char maps and editor char map encoding.
Manage Libraries...
It shows the updated list of all the installed libraries. We can also use this option to install a new library into the
Arduino IDE.
Serial Monitor
It allows the exchange of data with the connected board on the port.
Serial Plotter
The Serial Plotter button is used to display the serial data in a plot. It comes preinstalled in the Arduino IDE.
It is used to check and update the Wi-Fi Firmware of the connected board.
Board
We are required to select the board from the list of boards. The selected board must be similar to the board
connected to the computer.
Processor
It displays the processor according to the selected board. It refreshes every time during the selection of the board.
Port
It consists of the virtual and real serial devices present on our machine.
It gives the information about the selected board. We need to select the appropriate port before getting information
about the board.
Programmer
We need to select the hardware programmer while programming the board. It is required when we are not using the
onboard USB serial connection. It is also required during the burning of the Bootloader.
Burn Bootloader
The Bootloader is present on the board onto the microcontroller. The option is useful when we have purchased the
microcontroller without the bootloader. Before burning the bootloader, we need to make sure about the correct
selected board and port.
Help
When we click on the Help button on the Menu bar, a drop-down list will appear. It is shown below:
The Help section includes several documents that are easy to access, which comes along with the Arduino IDE. It
consists of the number of options such as Getting Started, Environment, Troubleshooting, Reference, etc. We can also
consider the image shown above, which includes all the options under the Help section.
Some documents like Getting started, Reference, etc., can be accessed without the internet connection as well. It will
directly link us to the official website of Arduino.
Arduino Kit
The Arduino Kit consists of all the components used for building digital or electronic devices. The Arduino boards are
also available in the form of DIY kits. Here, DIY specifies Do It Yourself. The DIY kits are created for teaching and as a
practice tool for students. The non-engineering students can also use such kits for their projects.
We can easily start with our electronics projects using the complete kit. It also helps us to create hand-on and
engaging projects. The kit helps in understanding the fundamentals of programming, voltage, current, and digital
logic. The concept of digital and analog signals can be understood by the implementation of actuators and sensors in
the projects.
Some of the Arduino projects are the Spaceship Interface (designing the control panel for spaceship), Keyboard
Instrument, Knock Lock (a secret code, which is used to open the door), etc.
There are various types of Arduino kits available in the market. Let's discuss some of the Arduino kits:
The Starter kit is generally the basic kit for freshers in the Electronics stream. It is based on the Arduino UNO board.
o Breadboard
o LED (Bright White, Green, Red, Yellow, Blue, and RGB)
o LCD Alphanumeric
o 9V Battery
o Resistors of 220 Ohms, 560 Ohms, 1kOhms, 4.7kOhms, 10kOhms, 1MOhms, and 10MOhms
o Diodes
o Optocouplers
o Piezo Capsule
o Push Buttons
o Tilt Sensor
o Potentiometer
o Phototransistor
o Temperature Sensor
o MOSFET Transistors
o USB Cable
Unit: 1
The Arduino UNO is a standard board of Arduino. Arduino UNO is based on an ATmega328P Microcontroller. It is
easy to use compared to other boards, such as the Arduino Mega board, etc. The components on the Arduino board
are ATmega328P Microcontroller, ICSP pin, power LED indicator, Digital I/O pins, Analog pins, AREF pin, 16 MHz
crystal oscillator, GND pins, Vin pin, voltage regulator, Tx and Rx LED, USB, and a reset button.
A breadboard is defined as a rectangular shape board, which is made of plastic. It has tiny holes on it that are used to
insert the wires of the electronic components, such as LED, resistor, etc.
It does not require any soldering to attach the electronic components to the board. We need to join the components
using wire to allow electricity to move from one component to another.
Unit: 1
LED stands for Light Emitting Diode, which is defined as a semiconductor light source. The bright white LED produces
the white light, while other white lights produce a yellow hue.
When electrons combine with holes in the semiconductor, energy is released in the form of photons, which produces
light.
Green LED
Unit: 8
The Green LED (Light Emitting Diode) produces the green light when electricity is passed through its terminals. The
process is called electroluminescence.
Red LED
Unit: 8
The Red LED produces the red light when electricity is passed through its terminals.
Yellow LED
Unit: 8
The Yellow LED produces the yellow light when electricity is passed through its terminals.
Blue LED
Unit: 3
The Blue LED produces blue light when electricity is passed through its terminals.
RGB LED
Unit: 1
The RGB LED uses the combination of three colors (Red, Green, and Blue) to produce the light. The millions of hue of
lights can be created from the combination of these three universal colors.
The colors are generated by adjusting the brightness of each of the three colors by using the PWM pin.
LCD Alphanumeric
Unit: 1
The LCD (Liquid Crystal Display) is a digital display, which gives information in the form of letters or numbers. It is the
basic component in a kit.
Unit: 1
The wooden base is a compatible base that is used to assemble the Arduino board and Breadboard on its base.
Unit: 70
These are the most common wires used in the Breadboard. The wires vary in different lengths and colors. These
wires are cheap and come in the form of the spool. We need to cut the wire according to the required length.
Unit: 1
Unit: 1
9V Battery
Unit: 1
It is a standard-sized battery used for different purposes. A polarized snap is connected at the top of the rectangle-
shaped battery.
Resistors of 220 Ohms, 560 Ohms, 1kOhms, 4.7kOhms, 10kOhms, 1MOhms, and 10MOhms
Unit: 20 (220 Ohms), 5 (560 Ohms), 5 (1kOhms), 5 (4.7kOhms), 20 (10kOhms), 5 (1MOhms), 5 (10MOhms)
The function of the resistor is to manage the current flow. It controls the current flowing to the other components.
The other functions are dividing voltages, adjusting the signal levels, etc.
Unit: 1
Unit: 1
The standard pitch for the 40 x 1 connector pin is 2.54mm. It is a single row male pin consisting of 40 pin headers
connected to it.
It is shown below:
Red, Blue, and Green Transparent Gels
Unit: 3
The colored gels act as a filter for the sensors, which allows the specific colored light to pass through that gel.
Diodes (1N4007)
Unit: 5
A diode conducts the current in one direction. The diode is an electronic component that has two terminals. The
diodes can be used as the signal modulators, and demodulators, switches, voltage regulators, etc.
Unit: 5
The capacitor is a device that stores electrical energy. The energy is stored between the plates of the capacitor in the
form of an electrostatic field.
Optocouplers
Unit: 1
The noise from the electrical signals is removed by the Optocouplers. It is also used to separate the low power
circuits from the high-power circuits and transfers the electrical signals between these separated circuits.
Unit: 1
The servo motor is used to control the position, liner speed, and rotational speed. The advantageous features of
servo motor are high efficiency, high precision, low heat generation, etc.
Piezo Capsule
Unit: 1
The piezo in Arduino is defined as an electronic device, which produces a voltage when deformed by some
mechanical strain, sound wave, or a vibration.
Push Buttons
Unit: 10
The push buttons are used as a switch. We can power ON the board supply or the connection by pressing the push
button.
Tilt Sensor
Unit: 1
The tilt sensor is used to measure the tilt with respect to the reference plain. It is also used to detect the inclination
of the plane.
Potentiometer (10kOhms)
Unit: 3
The potentiometer acts as a knob, which is used to provide variable resistance. It can also be used to alter its
resistance. The amount of resistance is measured as an analog value.
Phototransistor
Unit: 6
The phototransistor uses the NPN transistors to sense the light level and convert it into the current.
Temperature Sensor
Unit: 1
The temperature sensors are used to record the surrounding temperature. It converts the input data to the electronic
data.
Mosfet Transistors
Unit: 2
We can control the high voltage Arduino projects using the Mosfet Transistors. One terminal is used as a power
source, and the other two terminals are used onboard.
Unit: 1
These motors are capable of driving the DC motors. We can turn the motor in both directions with the help of an H-
bridge motor driver.
USB Cable
Unit: 1
The Universal Serial Bus (USB) is a cable that is used to connect the Arduino board with the computer. We can further
program the Arduino board through the Arduino IDE on our computer.
It includes a CD, which consist of a PDF explaining about the specifications of the kit. It consists of some additional
components, such as a joystick, Infrared Receiver, and Remote. The beginners may face some difficulty while using
such kit.
It is the ultimate kit intended for professionals. Beginners with advanced knowledge can use it.
The components in the kit are listed below:
Arduino Uno R3, Temperature Sensor TMP36, USB Cable, Shift Register, Arduino, Breadboard & its Holder, NPN
Transistors, Small Servo motor, 5V Relay, Jumper Wires, DC Motor with wires, Piezo Buzzer, 12 units of Big 12mm
Buttons, Photocell, LEDs (1x RGB, 10 x Red, 10 x Yellow), 10K Trimpot, Resistors (45 x 330Ω and 45 x 10KΩ), and 2
units of 1N4148 Diodes.
It includes a vast collection of components. The components in the kit are listed below:
MEGA2560 Controller Board, IR Receiver, Button (small) (5), Power Supply Module, Stepper Motor, Humiture Sensor,
4-Digit 7-Segment Display, Dupont wire (Female to Male) (10), 5V Relay, Remote Control, Servo Motor (SG90), USB
Cable (5), Stepper Motor Driver, Jumper Wire (Male to Male) (65), 9V Battery Clip Connector, Joystick PS2,
Breadboard, Thermistor, Capacitor Ceramic 100nF, Photoresistor, Tilt Switch, Active Buzzer, LCD1602 Character
Display LEDs(5 x Yellow, 5 x Red, 5 x Green, 5 x Blue, 5 x White, 1 x RGB, Resistors (10 each 10Ω, 100Ω, 220Ω, 330Ω,
1KΩ, 2KΩ, 5.1KΩ, 10KΩ, 100KΩ, 1MΩ), Potentiometer, NPN Transistor, Small Motor, Fan, and Ultrasonic Sensor
Module.
Arduino Shields
Arduino shields are the boards, which are plugged over the Arduino board to expand its functionalities. There are
different varieties of shields used for various tasks, such as Arduino motor shields, Arduino communication shields,
etc.
Shield is defined as the hardware device that can be mounted over the board to increase the capabilities of the
projects. It also makes our work easy. For example, Ethernet shields are used to connect the Arduino board to
the Internet.
The pin position of the shields is similar to the Arduino boards. We can also connect the modules and sensors to the
shields with the help of the connection cable.
Arduino motor shields help us to control the motors with the Arduino board.
o The shields can be attached and detached easily from the Arduino board. It does not require any complex
wiring.
o It is easy to connect the shields by mounting them over the Arduino board.
Types of Shields
o Ethernet shield
o Xbee Shield
o Proto shield
o Relay shield
o Motor shield
o LCD shield
o Bluetooth shield
Ethernet shield
o The Ethernet shields are used to connect the Arduino board to the Internet. We need to mount the shield on
the top of the specified Arduino board.
o The USB port will play the usual role to upload sketches on the board.
o The latest version of Ethernet shields consists of a micro SD card slot. The micro SD card slot can be
interfaced with the help of the SD card library.
Xbee Shield
o We can communicate wirelessly with the Arduino board by using the Xbee Shield with Zigbee.
o It reduces the hassle of the cable, which makes Xbee a wireless communication model.
o The Xbee wireless module allows us to communicate outdoor upto 300 feet and indoor upto 100 feet.
Proto shield
o The shield consists of two LED pads, two power lines, and SPI signal pads.
o The IOREF (Input Output voltage REFerence) and GND (Ground) are the two power lines on the board.
The proto shield is shown below:
o We can also solder the SMD (Surface Mount Device) ICs on the prototyping area. A maximum of 24 pins can
be integrated onto the SMD area.
Relay shield
o The Arduino digital I/O pins cannot bear the high current due to its voltage and current limits. The relay
shield is used to overcome such situation. It provides a solution for controlling the devices carrying high
current and voltage.
o It also provides NO/NC interfaces and a shield form factor for the simple connection to the Arduino board.
o The NO (Normally Open), NC (Normally Closed), and COM pins are present on each relay.
Motor shield
o The motor shield helps us to control the motor using the Arduino board.
o It controls the direction and working speed of the motor. We can power the motor shield either by the
external power supply through the input terminal or directly by the Arduino.
o We can also measure the absorption current of each motor with the help of the motor shield.
o The motor shield is based on the L298 chip that can drive a step motor or two DC motors. L298 chip is a full
bridge IC. It also consists of the heat sinker, which increases the performance of the motor shield.
o It can drive inductive loads, such as solenoids, etc.
o The applications of the motor shield are intelligent vehicles, micro-robots, etc.
LCD shield
o The keypad of LCD (Liquid Crystal Display) shield includes five buttons called as up, down, left, right, and
select.
o There are 6 push buttons present on the shield that can be used as a custom menu control panel.
o It consists of the 1602 white characters, which are displayed on the blue backlight LCD.
o The five keys present on the board helps us to make the selection on menus and from board to our project.
o The LCD shield is popularly designed for the classic boards such as Duemilanove, UNO, etc.
Bluetooth shield
o The Bluetooth shield can be used as a wireless module for transparent serial communication.
o It includes a serial Bluetooth module. D0 and D1 are the serial hardware ports in the Bluetooth shield, which
can be used to communicate with the two serial ports (from D0 to D7) of the Arduino board.
o We can install Groves through the two serial ports of the Bluetooth shield called a Grove connector. One
Grove connector is digital, while the other is analog.
o It has a touchpad interface that allows to integrate the Arduino board with the touch shield.
o The Capacitive touchpad shield consists of 12 sensitive touch buttons, which includes 3 electrode
connections and 9 capacitive touch pads.
o The board can work with the logic level of 3.3V or 5V.
Arduino is an easy-to-use open platform to create electronics projects. Arduino boards play a vital role in creating
different projects. It makes electronics accessible to non-engineers, hobbyists, etc.
The various components present on the Arduino boards are Microcontroller, Digital Input/output pins, USB
Interface and Connector, Analog Pins, Reset Button, Power button, LED's, Crystal Oscillator, and Voltage Regulator.
Some components may differ depending on the type of board.
The most standard and popular board used over time is Arduino UNO. The ATmega328 Microcontroller present on
the UNO board makes it rather powerful than other boards. There are various types of Arduino boards used for
different purposes and projects. The Arduino Boards are organized using the Arduino (IDE), which can run on various
platforms. Here, IDE stands for Integrated Development Environment.
o Arduino UNO
Arduino UNO is based on an ATmega328P microcontroller. It is easy to use compared to other boards, such as the
Arduino Mega board, etc. The Arduino UNO includes 6 analog pin inputs, 14 digital pins, a USB connector, a power
jack, and an ICSP (In-Circuit Serial Programming) header.
It is the most used and of standard form from the list of all available Arduino Boards. It is also recommended for
beginners as it is easy to use.
o Arduino Nano
The Arduino Nano is a small Arduino board based on ATmega328P or ATmega628 Microcontroller. The connectivity is
the same as the Arduino UNO board.
The Nano board is defined as a sustainable, small, consistent, and flexible microcontroller board. It is small in size
compared to the UNO board. The devices required to start our projects using the Arduino Nano board are Arduino
IDE and mini USB.
The Arduino Nano includes an I/O pin set of 14 digital pins and 8 analog pins. It also includes 6 Power pins and 2
Reset pins.
o Arduino Mega
The Arduino Mega is based on ATmega2560 Microcontroller. The ATmega2560 is an 8-bit microcontroller. We need a
simple USB cable to connect to the computer and the AC to DC adapter or battery to get started with it. It has the
advantage of working with more memory space.
The Arduino Mega includes 54 I/O digital pins and 16 Analog Input/Output (I/O), ICSP header, a reset button, 4 UART
(Universal Asynchronous Reciever/Transmitter) ports, USB connection, and a power jack.
o Arduino Micro
The Arduino Micro is based on the ATmega32U4 Microcontroller. It consists of 20 sets of pins. The 7 pins from the set
are PWM (Pulse Width Modulation) pins, while 12 pins are analog input pins. The other components on board are
reset button, 16MHz crystal oscillator, ICSP header, and a micro USB connection.
The Arduino Micro is also called as the shrunk version of Arduino Leonardo.
o Arduino Leonardo
The basic specification of the Arduino Leonardo is the same as the Arduino Micro. It is also based on ATmega32U4
Microcontroller. The components present on the board are 20 analog and digital pins, reset button, 16MHz crystal
oscillator, ICSP header, and a micro USB connection.
o Arduino Due
The Arduino Due is based on the 32- bit ARM core. It is the first Arduino board that has developed based on the ARM
Microcontroller. It consists of 54 Digital Input/Output pins and 12 Analog pins. The Microcontroller present on the
board is the Atmel SAM3X8E ARM Cortex-M3 CPU.
It has two ports, namely, native USB port and Programming port. The micro side of the USB cable should be attached
to the programming port.
o Arduino Shields
The Arduino shields are the boards, which can be plugged on the top of the PCB. The shields further extend the
potential of the PCB's. The production of shields is cheap. It is also easy to use. There are various types of Arduino
shields that can be used for different purposes. For example, the Xbee shield.
The Xbee shield can be used for wireless communication between multiple Arduino boards over distances upto 300
feet using the Zigbee Module.
o Arduino Lilypad
The Arduino LilyPad was initially created for wearable projects and e-textiles. It is based on the ATmega168
Microcontroller. The functionality of Lilypad is the same as other Arduino Boards. It is a round, light-weight board
with a minimal number of components to keep the size of board small.
The Arduino Lilypad board was designed by Sparkfun and Leah. It was developed by Leah Buechley. It has 9 digital I/O
pins.
o Arduino Bluetooth
The Arduino Bluetooth board is based on ATmega168 Microcontroller. It is also named as Arduino BT board. The
components present on the board are 16 digital pins, 6 analog pins, reset button, 16MHz crystal oscillator, ICSP
header, and screw terminals. The screw terminals are used for power.
The Arduino Bluetooth Microcontroller board can be programmed over the Bluetooth as a wireless connection.
o Arduino Diecimila
The Arduino Diecimila is also based on ATmeg628 Microcontroller. The board consists of 6 analog pin inputs, 14
digital Input/Output pins, a USB connector, a power jack, an ICSP (In-Circuit Serial Programming) header, and a reset
button.
We can connect the board to the computer using the USB, and can power-on the board with the help of AC to DC
adapter. The Diecimila was initially developed to mark the 10000 delivered boards of Arduino. Here, Diecimila means
10,000 in Italian.
o Arduino Robot
The Arduino Robot is called as the tiny computer. It is widely used in robotics. The board comprises of the speaker,
five-button, color screen, two motors, an SD card reader, a digital compass, two potentiometers, and five floor
sensors.
The Robot Library can be used to control the actuators and the sensors.
o Arduino Ethernet
The Arduino Ethernet is based on the ATmega328 Microcontroller. The board consists of 6 analog pins, 14 digital I/O
pins, crystal oscillator, reset button, ICSP header, a power jack, and an RJ45 connection.
With the help of the Ethernet shield, we can connect our Arduino board to the internet.
o Arduino Zero
The Arduino Zero is generally called as the 32-bit extension of the Arduino UNO. It is based on ATmel's SAM21 MCU.
The board consists of 6 analog pin inputs, 14 digital Input/Output pins, a USB connector, a power jack, and an ICSP
(In-Circuit Serial Programming) header, UART port pins, a power header, and AREF button.
The Embedded debugger of Atmel is also supported by the Arduino Zero. The function of Debugger is to provide a
full debug interface, which does not require additional hardware.
o Arduino Esplora
The Arduino Esplora boards allow easy interfacing of sensors and actuators. The outputs and inputs connected on the
Esplora board make it unique from other types of Arduino boards. The board includes outputs, inputs, a small
microcontroller, a microphone, a sensor, a joystick, an accelerometer, a temperature sensor, four buttons, and a
slider.
o Arduino Pro Micro
The structure of Arduino Pro Micro is similar to the Arduino Mini board, except the Microcontroller ATmega32U4.
The board consists of 12 digital Input/output pins, 5 PWM (Pulse Width Modulation) pins, Tx and Rx serial
connections, and 10-bit ADC (Analog to Digital Converter).
The list of boards that we can see in the Arduino software is shown below:
Here, the dot represents the select Arduino board in the Arduino IDE.
Arduino UNO
The Arduino UNO is a standard board of Arduino. Here UNO means 'one' in Italian. It was named as UNO to label the
first release of Arduino Software. It was also the first USB board released by Arduino. It is considered as the powerful
board used in various projects. Arduino.cc developed the Arduino UNO board.
Arduino UNO is based on an ATmega328P microcontroller. It is easy to use compared to other boards, such as the
Arduino Mega board, etc. The board consists of digital and analog Input/Output pins (I/O), shields, and other circuits.
The Arduino UNO includes 6 analog pin inputs, 14 digital pins, a USB connector, a power jack, and an ICSP (In-Circuit
Serial Programming) header. It is programmed based on IDE, which stands for Integrated Development Environment.
It can run on both online and offline platforms.
o ATmega328 Microcontroller- It is a single chip Microcontroller of the ATmel family. The processor code inside
it is of 8-bit. It combines Memory (SRAM, EEPROM, and Flash), Analog to Digital Converter, SPI serial ports,
I/O lines, registers, timer, external and internal interrupts, and oscillator.
o ICSP pin - The In-Circuit Serial Programming pin allows the user to program using the firmware of the
Arduino board.
o Power LED Indicator- The ON status of LED shows the power is activated. When the power is OFF, the LED
will not light up.
o Digital I/O pins- The digital pins have the value HIGH or LOW. The pins numbered from D0 to D13 are digital
pins.
o TX and RX LED's- The successful flow of data is represented by the lighting of these LED's.
o AREF- The Analog Reference (AREF) pin is used to feed a reference voltage to the Arduino UNO board from
the external power supply.
o USB- It allows the board to connect to the computer. It is essential for the programming of the Arduino UNO
board.
o Crystal Oscillator- The Crystal oscillator has a frequency of 16MHz, which makes the Arduino UNO a powerful
board.
o Voltage Regulator- The voltage regulator converts the input voltage to 5V.
o GND- Ground pins. The ground pin acts as a pin with zero voltage.
The USB port in the Arduino board is used to connect the board to the computer using the USB cable. The cable acts
as a serial port and as the power supply to interface the board. Such dual functioning makes it unique to recommend
and easy to use for beginners.
What is the main difference between Arduino UNO and Arduino Nano?
The Arduino Nano has a compact size and mini USB cable than the Arduino UNO.
What is the main difference between Arduino UNO and Arduino Mega?
The Arduino UNO is a standard board recommended to beginners, while Arduino Mega is used for complex projects
due to its greater memory space.
Memory
The preinstalled flash has a bootloader, which takes the memory of 0.5 Kb.
Here, SRAM stands for Static Random Access Memory, and EEPROM stands for Electrically Erasable Programmable
Read-Only Memory.
o There are 20 Input/Output pins present on the Arduino UNO board. These 20 pis include 6 PWM pins, 6
analog pins, and 8 digital I/O pins.
o The crystal oscillator present in Arduino UNO comes with a frequency of 16MHz.
o It also has a Arduino integrated WiFi module. Such Arduino UNO board is based on the Integrated WiFi
ESP8266 Module and ATmega328P microcontroller.
o The input voltage of the UNO board varies from 7V to 20V.
o Arduino UNO automatically draws power from the external power supply. It can also draw power from the
USB.
We can program the Arduino UNO using the Arduino IDE. The Arduino IDE is the Integral Development program,
which is common to all the boards.
We can also use Arduino Web Editor, which allows us to upload sketches and write the code from our web browser
(Google Chrome recommended) to any Arduino Board. It is an online platform.
The USB connection is essential to connect the computer with the board. After the connection, the PWR pins will
light in green. It is a green power LED.
The steps to get started with Arduino UNO are listed below:
As soon we connect the board to the computer, Windows from XP to 10 will automatically install the board drivers.
But, if you have expanded or downloaded the zip package, follow the below steps:
2. Click on System -> Device Manager -> Ports (COM &LPT) -> Arduino UNO (COMxx). If the COM &LPT is
absent, look Other Devices -> Unknown Device.
3. Right-click to Arduino UNO (COmxx) -> Update Driver Software -> Browse my computer for driver software.
5. Installation Finished.
o Select the port. Click on the Tools -> Port (select the port). The port likely will be COM3 or higher. For
example, COM6, etc. The COM1 and COM2 ports will not appear, because these two ports are reserved for
the hardware serial ports.
To upload and run, click on the button present on the top panel of the Arduino display, as shown below:
Within the few seconds after the compile and run of code or sketch, the RX and TX light present on the Arduino
board will flash.
The 'Done Uploading' message will appear after the code is successfully uploaded. The message will be visible in the
status bar.
Arduino UNO Pinout
The Arduino UNO is a standard board of Arduino, which is based on an ATmega328P microcontroller. It is easier to
use than other types of Arduino Boards.
The Arduino UNO Board, with the specification of pins, is shown below:
o ATmega328 Microcontroller- It is a single chip Microcontroller of the ATmel family. The processor core inside
it is of 8-bit. It is a low-cost, low powered, and a simple microcontroller. The Arduino UNO and Nano models
are based on the ATmega328 Microcontroller.
o Voltage Regulator
The voltage regulator converts the input voltage to 5V. The primary function of voltage regulator is to regulate the
voltage level in the Arduino board. For any changes in the input voltage of the regulator, the output voltage is
constant and steady.
o GND - Ground pins. The ground pins are used to ground the circuit.
o USB Interface
The USB Interface is used to plug-in the USB cable. It allows the board to connect to the computer. It is essential for
the programming of the Arduino UNO board.
o RESET
o SCK
It stands for Serial Clock. These are the clock pulses, which are used to synchronize the transmission of data.
o MISO
It stands for Master Input/ Slave Output. The save line in the MISO pin is used to send the data to the master.
o VCC
It is the modulated DC supply voltage, which is used to regulate the IC's used in the connection. It is also called as the
primary voltage for IC's present on the Arduino board. The Vcc voltage value can be negative or positive with respect
to the GND pin.
o Crystal Oscillator- The Crystal oscillator has a frequency of 16MHz, which makes the Arduino UNO a powerful
board.
o ICSP
It stands for In-Circuit Serial Programming. The users can program the Arduino board's firmware using the ICSP pins.
The program or firmware with the advanced functionalities is received by microcontroller with the help of the ICSP
header.
o SDA
It stands for Serial Data. It is a line used by the slave and master to send and receive data. It is called as a data
line, while SCL is called as a clock line.
o SCL
It stands for Serial Clock. It is defined as the line that carries the clock data. It is used to synchronize the transfer of
data between the two devices. The Serial Clock is generated by the device and it is called as master.
o SPI
It stands for Serial Peripheral Interface. It is popularly used by the microcontrollers to communicate with one or
more peripheral devices quickly. It uses conductors for data receiving, data sending, synchronization, and device
selection (for communication).
o MOSI
o SS
It stands for Slave Select. It is the Slave Select line, which is used by the master. It acts as the enable line.
o I2C
It is the two-wire serial communication protocol. It stands for Inter Integrated Circuits. The I2C is a serial
communication protocol that uses SCL (Serial Clock) and SDA (Serial Data) to receive and send data between two
devices.
We have already discussed the popular Arduino Boards, Arduino IDEs, and Installation process of the Arduino
software. We learned that Arduino IDE (Integrated Development Environment) allows us to draw the sketch and
upload it to the various Arduino boards using code. The code is written in a simple programming language similar
to C and C++.
The initial step to start with Arduino is the IDE download and installation.
Brackets
There are two types of brackets used in the Arduino coding, which are listed below:
o Parentheses ( )
o Curly Brackets { }
Parentheses ( )
The parentheses brackets are the group of the arguments, such as method, function, or a code statement. These are
also used to group the math equations.
Curly Brackets { }
The statements in the code are enclosed in the curly brackets. We always require closed curly brackets to match the
open curly bracket in the code or sketch.
Line Comment
There are two types of line comments, which are listed below:
o Multi-line comment
The text that is written after the two forward slashes are considered as a single line comment. The compiler ignores
the code written after the two forward slashes. The comment will not be displayed in the output. Such text is
specified for a better understanding of the code or for the explanation of any code statement.
The // (two forward slashes) are also used to ignore some extra lines of code without deleting it.
The Multi-line comment is written to group the information for clear understanding. It starts with the single forward
slash and an asterisk symbol (/ *). It also ends with the / *. It is commonly used to write the larger text. It is a
comment, which is also ignored by the compiler.
Coding Screen
The coding screen is divided into two blocks. The setup is considered as the preparation block, while the loop is
considered as the execution block. It is shown below:
The set of statements in the setup and loop blocks are enclosed with the curly brackets. We can write multiple
statements depending on the coding requirements for a particular project.
For example:
1. void setup ( )
2. {
3. Coding statement 1;
4. Coding statement 2;
5. .
6. .
7. .
8. Coding statement n;
9. }
11. {
14. .
15. .
16. .
It contains an initial part of the code to be executed. The pin modes, libraries, variables, etc., are initialized in the
setup section. It is executed only once during the uploading of the program and after reset or power up of the
Arduino board.
Zero setup () resides at the top of each sketch. As soon as the program starts running, the code inside the curly
bracket is executed in the setup and it executes only once.
The loop contains statements that are executed repeatedly. The section of code inside the curly brackets is repeated
depending on the value of variables.
Time in Arduino
For example, for a 5-second delay, the time displayed will be 5000 milliseconds.
Example:
pinMode ( )
The specific pin number is set as the INPUT or OUTPUT in the pinMode () function.
Where,
pin: It is the pin number. We can select the pin number according to the requirements.
Mode: We can set the mode as INPUT or OUTPUT according to the corresponding pin number.
Code:
The OUTPUT mode of a specific pin number provides a considerable amount of current to other circuits, which is
enough to run a sensor or to light the LED brightly. The output state of a pin is considered as the low-impedance
state.
The high current and short circuit of a pin can damage the ATmel chip. So, it is recommended to set the mode as
OUTPUT.
The digitalWrite () will disable the LOW during the INPUT mode. The output pin will be considered as HIGH.
We can use the INPUT mode to use the external pull-down resistor. We are required to set the pinMode as
INPUT_PULLUP. It is used to reverse the nature of the INPUT mode.
The sufficient amount of current is provided by the pull-up mode to dimly light an LED, which is connected to the pin
in the INPUT mode. If the LED is working dimly, it means this condition is working out.
o The void loop () would include digitalWrite( ) and delay ( ) as the main function.
digitalWrite( )
The digitalWrite ( ) function is used to set the value of a pin as HIGH or LOW.
Where,
HIGH: It sets the value of the voltage. For the 5V board, it will set the value of 5V, while for 3.3V, it will set the value
of 3.3V.
If we do not set the pinMode as OUTPUT, the LED may light dim.
The HIGH will ON the LED and LOW will OFF the LED connected to pin number 13.
The digitalRead () function will read the HIGH/LOW value from the digital pin, and the digitalWrite () function is used
to set the HIGH/LOW value of the digital pin.
delay ( )
The delay () function is a blocking function to pause a program from doing a task during the specified duration in
milliseconds.
Code:
2. delay (2000);
4. delay (1000);
Here, the LED connected to pin number 13 will be ON for 2 seconds and OFF for 1 second. The task will repeatedly
execute as it is in the void loop ().
Example: To light the LED connected to pin number 13. We want to ON the LED for 4 seconds and OFF the LED for 1.5
seconds.
Code:
1. void setup ()
2. {
3. pinMode ( 13, OUTPUT); // to set the OUTPUT mode of pin number 13.
4. }
5. void loop ()
6. {
11. }
Arduino Syntax and Program Flow
Syntax
Syntax in Arduino signifies the rules need to be followed for the successful uploading of the Arduino program to the
board. The syntax of Arduino is similar to the grammar in English. It means that the rules must be followed in order
to compile and run our code successfully. If we break those rules, our computer program may compile and run, but
with some bugs.
As we open the Arduino IDE, the display will look like the below image:
The two functions that encapsulate the pieces of code in the Arduino program are shown below:
1. void setup ( )
2. void loop ( )
Functions
o The functions in Arduino combine many pieces of lines of code into one.
o The functions usually return a value after finishing execution. But here, the function does not return any
value due to the presence of void.
o The setup and loop function have void keyword present in front of their function name.
o The multiple lines of code that a function encapsulates are written inside curly brackets.
o Every closing curly bracket ' } ' must match the opening curly bracket '{ ' in the code.
o We can also write our own functions, which will be discussed later in this tutorial.
Spaces
o Arduino ignores the white spaces and tabs before the coding statements.
o The coding statements in the code are intent (empty spacing at the starting) for the easy reading.
o The compiler of Arduino also ignores the spaces in the parentheses, commas, blank lines, etc.
Tools Tab
o The verify icon present on the tool tab only compiles the code. It is a quick method to check that whether the
syntax of our program is correct or not.
o To compile, run, and upload the code to the board, we need to click on the Upload button.
Uses of Parentheses ( )
o The parameter's inputs to the function are enclosed within the parentheses.
Semicolon ;
o A statement is a command given to the Arduino, which instructs it to take some kind of action. Hence, the
terminator is essential to signify the end of a statement.
o We can write one or more statements in a single line, but with semicolon indicating the end of each
statement.
o The compiler will indicate an error if a semicolon is absent in any of the statements.
o It is recommended to write each statement with semicolon in a different line, which makes the code easier to
read.
o We are not required to place a semicolon after the curly braces of the setup and loop function.
Arduino processes each statement sequentially. It executes one statement at a time before moving to the next
statement.
Program Flow
The program flow in Arduino is similar to the flowcharts. It represents the execution of a program in order.
We recommend to draw the flowchart before writing the code. It helps us to understand the concept of code, which
makes it the coding simpler and easier.
Flow Charts
A flowchart uses shapes and arrows to represent the information or sequence of actions.
An oval ellipse shows the Start of the sequence, and a square shows the action or processes that need to be
performed.
The Arduino coding process in the form of the flowchart is shown below:
Here, the processor enters our code, and the execution of code begins. After the setup, the execution of the
statement in the loop begins.
The example of the flowchart in Arduino is shown below:
Arduino Serial |Serial.begin()
Serial Communication
The serial communication is a simple scheme that uses the UART (Universal Asynchronous Receiver/Transmitter) on
the Microcontroller. It uses,
Every message sent on the UART is in the form of 8 bits or 1 byte, where 1 byte = 8 bits.
The messages sent to the computer from Arduino are sent from PIN 1 of the Arduino board, called Tx (Transmitter).
The messages being sent to the Arduino from the computer are received on PIN 0, called Rx (Receiver).
These two pins on the Arduino UNO board look like the below image:
When we initialize the pins for serial communication in our code, we cannot use these two pins (Rx and Tx) for any
purpose. The Tx and Rx pins are also connected directly to the computer.
The pins are connected to the serial Tx and Rx chip, which acts as a serial to USB translator. It acts as a medium for
the computer to talk to the Microcontroller.
The object can include any number of data members (information) and member functions (to call actions).
The Serial.begin( ) is a part of the serial object in the Arduino. It tells the serial object to perform initialization steps
to send and receive data on the Rx and Tx (pins 1 and 0).
Let's discuss Serial.begin( ) in detail.
Arduino Mega has four serial ports. The Tx pins on the Mega board are listed below:
o 1 (TX)
o 18 (TX)
o 16 (TX)
o 14 (TX)
o 0 (RX)
o 19 (RX)
o 17 (RX)
o 15 (RX)
The communication with the Tx and Rx pins would cause interference and failed uploads to the particular board.
If we require a serial port for communication, we need to use a USB-to serial adapter. It is a mini USB connector,
which converts the USB connection to the Serial RX and TX. We can directly connect the adapter to the board.
There are five pins present on the USB-to serial adapter, including RX, TX, reset button, and GND (Ground).
Serial.begin ( )
The serial.begin( ) sets the baud rate for serial data communication. The baud rate signifies the data rate in bits per
second.
The default baud rate in Arduino is 9600 bps (bits per second). We can specify other baud rates as well, such as 4800,
14400, 38400, 28800, etc.
o begin( speed )
Where,
speed: It signifies the baud rate or bps (bits per second) rate. It allows long data types.
Example 1:
1. void setup ( )
2. {
3. Serial.begin(4800);
4. }
5. void loop ( )
6. {
7. }
The serial.begin (4800 ) open the serial port and set the bits per rate to 4800. The messages in Arduino are
interchanged with the serial monitor at a rate of 4800 bits per second.
Example 2:
It is shown below:
Arduino Serial.print ( )
The serial.print ( ) in Arduino prints the data to the serial port. The printed data is stored in the ASCII (American
Standard Code for Information Interchange) format, which is a human-readable text.
The printed data will be visible in the serial monitor, which is present on the right corner on the toolbar.
o print( value )
Where,
value: It signifies the value to print, which includes any data type value.
format: It consists of number base, such as OCT (Octal), BIN (Binary), HEX (Hexadecimal), etc. for the integral data
types. It also specifies the number of decimal places.
Serial.print( value )
The serial.print ( ) accepts the number using the ASCII character per digit and value upto two decimal places for
floating point numbers.
Example 1:
1. Serial.print(15.452732)
Output:
15.45
It sends bytes to the printer as a single character. In Arduino, the strings and characters using the Serial.print( ) are
sent as it is.
Example 2:
1. Serial.print("Hello Arduino")
Output:
"Hello Arduino"
It specifies the base format and gives the output according to the specified format. It includes the formats Octal -OCT
(base 8), Binary-BIN (base 2), Decimal-DEC (base 10), and Hexadecimal-HEX (base 16).
Example 1:
1. Serial.print(25, BIN)
Output:
11001
Example 2:
1. Serial.print(58, HEX)
Output:
3A
Example 3:
1. Serial.print(58, OCT)
Output:
72
Example 4:
1. Serial.print(25, DEC)
Output:
25
The conversion is from decimal to decimal. So, the output will be the same.
If we want to pass the flash memory in Serial.print ( ) based on string, we need to wrap the function statement
with F.
For example,
Serial.print( F ( "Hello Arduino") ).
1. void setup ( )
2. {
3. Serial.begin ( 4800);
4. }
5. void loop ( )
6. {
8. Serial.print(" \ t '');
9. }
Here, Serial.print(" \ t '') is used to print the tab in the output program.
Serial.println ( )
The Serial.println ( ) means print line, which sends the string followed by the carriage return ('\r' or ASCII 13) and
newline ('\n' or ASCII 10) characters. It has a similar effect as pressing the Enter or Return key on the keyboard when
typing with the Text Editor.
The Serial.println( ) is also declared in two formats, which are shown below:
o println( value )
The text written inside the open and closed parentheses in the Serial.println( ) moves in a new line. With the help of
Serial.print( ) and Serial.println( ), we can figure the order and execution of certain things in our code.
1. void setup ( )
2. {
3. Serial.begin ( 4800);
4. }
5. void loop ( )
6. {
7. Serial.print(" Hello");
8. delay(1000);
9. Serial.println("Arduino"); // It will print Arduino followed by a new line.
10. delay ( 1500); // delay of 1.5 seconds between each printed line.
11. }
In the output, the word Hello will appear followed by the word Arduino 1 second later. After 1.5 second, another line
will be printed.
Output
1. Hello Arduino
2. Hello Arduino // The next line will be printed after the specified duration.
3. .
4. .
5. .
6. .
Arduino Mega
The Arduino Mega board (type of Arduino board) has four serial ports. While programming the Mega, we need to
declare all the four serial ports. The baud rates of all the four serial ports should be different.
It is shown below:
1. void setup() {
2. Serial.begin(4800);
3. Serial1.begin(28800);
4. Serial2.begin(38400);
5. Serial3.begin(9600);
6.
7. Serial.println("Serial port");
11. }
13. {
14. }
Serial.available( )
The Serial.available( ) function in Arduino gets the stored bytes from the serial port that are available for reading. It
is the data, which is already stored and arrived in the serial buffer. The serial buffer in Arduino holds the 64 bytes.
Serial.available( ) function inherits from the utility class called stream. The stream is only invoked when the function
relying on it is called. The stream class is considered as the base class for binary and character-based streams.
2. void setup( )
3. {
5. }
7. {
8. if(Serial.available( ) > 0) // It will only send data when the received data is greater than 0.
9. {
10. arrivingdatabyte = Serial.read( ); // It will read the incoming or arriving data byte
13. }
14. }
Serial1.available( )
Serial2.available( )
Serial3.available( )
In this example, the data will be read and sent from one port to another.
It will read data from port 0 and will then send the data to port 1.
Consider the below code.
1. void setup( )
2. {
3. Serial.begin(4800);
4. Serial1.begin(4800);
5. }
7. //In first, if the data is available in the port 0, it will send to the port 1. In second, if the data is available in the
port 1, it will send to the port 0.
8. void loop( )
9. {
10. // Now,the data will be read from port 0 and will be sent to the port 1.
12. {
15. }
16. // Now,the data will be read from port 1 and will be sent to the port 0.
18. {
21. }
22. }
We can also check the errors in our code by compiling. For that, click on the Verify button.
Note: With the help of the Arduino board, we cannot connect the serial device to our computer.
Arduino Serial.read( ) and Serial.write( )
Arduino Serial.read( )
The Serial.read( ) in Arduino reads the incoming serial data in the Arduino. The int data type is used here. It returns
the first data byte of the arriving serial data. It also returns -1 when no data is available on the serial port.
Where,
1. int arrivingdatabyte;
2. void setup( )
3. {
4. Serial.begin(9600);
5. }
6. void loop( )
7. {
8. if(Serial.available( ) > 0)
9. {
10. arrivingdatabyte = Serial.read( ); // It will read the incoming or arriving data byte
12. Serial.println(arrivingdatabyte);
13. }
14. }
The above code clearly explains that the Serial.available( ) is used to get the available number of bytes if it is greater
than 0. The Serial.read( ) function will read the data from the data byte and print a message if the data is received.
The data is sent from the serial monitor to the Arduino.
Serial.readString( )
It reads the incoming serial data from the serial buffer in the string. The String data type is used here.
1. String b;
2. void setup( )
3. {
4. Serial.begin(4800);
5. }
6. void loop( )
7. {
8. while( Serial.available( ) )
9. {
10. b = Serial.readString( );
11. Serial.println(b);
12. }
13. }
The above code clearly explains that the Serial.readString( ) is used to read the serial data into the string. The string
specified here is b.
The data in the Serial function is read as a string in the above code.
The Serial.read( ) function reads the data in terms of bytes, while the Serial.readString( ) reads the data in the term of
string.
Serial.write( )
It sends the binary data to the serial port in Arduino. The data through Serial.write is sent as a series of bytes or a
single byte. The data type is size_t.
o write( str )
o write( value )
Where,
str: The str means string, which sends the data as a series of bytes.
len: It signifies the number of bytes, which can be sent from the array.
1. void setup( )
2. {
3. Serial.begin(14400);
4. }
5. void loop( )
6. {
12. }
Arduino analogRead ( )
The analogRead( ) function reads the value from the specified analog pin present on the particular Arduino board.
The ADC (Analog to Digital Converter) on the Arduino board is a multichannel converter. It maps the input voltage
and the operating voltage between the values 0 and 1023. The operating voltage can be 5V or 3.3V.
The values from 0 to 1023 are the integer values. It can also be written as 0 to (2^10) -1.
The time duration to read an analog input signal on the boards (UNO, Mega, Mini, and Nano) is about 100
microseconds or 0.0001 seconds.
Hence, the maximum reading rate of analog input is about 10000 times per second.
o The Operating voltage of Arduino UNO, Mini, Mega, Nano, Leonardo, and Micro is 5V, and resolution is 10
bits.
o The Operating voltage of MKR family boards, Arduino Due, and Zero is 3 V, and resolution is 12 bits.
o On a particular board, we can change the input voltage using the analogReference( ) function.
analogReference( )
The reference voltage used for the analog input is configured by the analogReference( ).
1. analogReference (type)
Note: The external reference voltage on the AREF pin should not exceed greater than 5V or less than 0V. We need to
set the analog Reference as External while working on the AREF pin.
Otherwise, it can damage the microcontroller present on the Arduino board.
o We can change the resolution only for the MKR Family, Zero, and Due board using the
analogReadResolution( ) function.
analogReadResolution( )
The MKR Family, Zero, and Due have the ADC resolution of 12 bits.
The analogReadResolution( ) will return the integer values between 0 and 4095 from the analogRead( ) function.
1. analogReadResolution (bits)
where,
bits: It signifies the resolution bits returned by the analogRead( ) function. We can set the value of bits between 1
and 32.
Note: If the resolution bits higher than the board capabilities are specified, the Arduino will pad the extra bits with
zeroes.
For example, analogReadResolution (14)
The above function will give a 14-bit approximated number with the first two 12 bits (that includes ADC reading) and
the last two padded bits.
Syntax of analogRead ( )
1. analogRead(pin)
where,
pin: It includes the name of the particular analog pin to read from.
A not-connected analog pin can also return some value. Such value depends on the position of our hand on the
board and other nearby analog inputs.
Code Example
4. void setup()
5. {
7. }
8. void loop()
9. {
11. Serial.println(value);
12. }
The above code reads the voltage from the specified analog pin (AnaPin) and displays it.
Arduino Functions
The functions allow a programmer to divide a specific code into various sections, and each section performs a
particular task. The functions are created to perform a task multiple times in a program.
The function is a type of procedure that returns the area of code from which it is called.
For example, to repeat a task multiple times in code, we can use the same set of statements every time the task is
performed.
Let's discuss some advantages of using functions in programming, which are listed below:
The Arduino has two common functions setup() and loop(), which are called automatically in the background. The
code to be executed is written inside the curly braces within these functions.
void setup() - It includes the initial part of the code, which is executed only once. It is called as the preparation block.
void loop() - It includes the statements, which are executed repeatedly. It is called the execution block.
Function Declaration
We need a return type for a function. For example, we can store the return value of a function in a variable.
We can use any data type as a return type, such as float, char, etc.
o Function name
It consists of a name specified to the function. It represents the real body of the function.
o Function parameter
It includes the parameters passed to the function. The parameters are defined as the special variables, which are
used to pass data to a function.
Example 1:
1. void setup()
2. {
3. Serial.begin(9600);
4. }
5. void loop() {
7. int b = 4;
8. int c;
12. }
14. {
18. }
Example 3:
1. int a= 0;
2. int b;
3. void setup()
4. {
5. Serial.begin(9600);
6. }
7. void loop()
8. {
10. Serial.print(a);
12. if (b==1)
13. {
15. }
16. else
17. {
19. }
20.
21. a++; // the function will increment and will again run
22. delay(1000);
23. }
24.
28. {
29. return 1;
30. }
31. else
32. {
33. return 0;
34. }
35. }
Output:
and so on...
Arduino Data Types
The data types are used to identify the types of data and the associated functions for handling the data. It is used for
declaring functions and variables, which determines the bit pattern and the storage space.
The data types that we will use in the Arduino are listed below:
The void data type specifies the empty set of values and only used to declare the functions. It is used as the return
type for the functions that do not return any value.
1. int a = 3;
2. void setup( )
3. {
4. . //
5. }
6. void loop ( )
7. {
8. .
9. .
10. }
The integer data types are the whole numbers like 5, -6, 10, -123, etc. They do not have any fractional part. The
integer data types are represented by int. It is considered as the primary data type to store the numbers.
In the ATmega and Arduino UNO boards, the int data types store the value of 2 bytes.
On the boards like Arduino Zero and MKR1000 (SAMD boards), and Arduino Due, the int data type stores the value of
4 bytes or 32 bits. The Minimal range in such case would be - (2^ 31) to ((2 ^ 31) - 1) or -2,147,483,648 to
2,147,483,647.
The negative numbers are stored in the form of 2's complement, where the sign bit or the highest bit is flagged as
the negative number.
where,
var= variable
For example,
1. int a;
2. int b = 3;
Any variable or identifier becomes an integer variable and can hold only integer values.
1. int Sum = 0;
2. void setup( )
3. {
4. Serial.begin(9600);
5. }
6. void loop ( )
7. {
11. }
The char datatype can store any number of character set. An identifier declared as the char becomes a character
variable. The literals are written inside a single quote.
The char type is often said to be an integer type. It is because, symbols, letters, etc., are represented in memory by
associated number codes and that are only integers.
The size of character data type is minimum of 8 bits. We can use the byte data type for an unsigned char data type of
8 bits or 1 byte.
For example, character ' A ' has the ASCII value of 65.
where,
var= variable
A number having the fractional part and a decimal part is considered as a floating-point number. For example, 4.567
is a floating-point number. The number 13 is an integer, while 13.0 is a floating-point number. Due to their greater
resolution, fractional numbers are used to approximate the contiguous and analog values.
Floating point numbers can also be written in the exponent form. The numbers can be as large as 3.4028235E+38 and
as small as -3.4028235E+38. The size of float data types is 4 bytes or 32 bits.
where,
var= variable
1. int a ;
2. int b ;
3. float c ;
4. void setup ( )
5. {
6. Serial.begin (9600);
7. }
8. void loop ( )
9. {
10. a = 3 ;
14. }
Note: We need to add a decimal point to a number. Otherwise, it will be considered as an integer. For example, 14.0 is
considered as a float number, while 14 is an integer.
1. float a = 3.6 ;
The double data type is also used for handling the decimal or floating-point numbers. It occupies twice as much
memory as float. It stores floating point numbers with larger precision and range. It stands for double precision
floating point numbers.
It occupies 4 bytes in ATmega and UNO boards, while 8 bytes on Arduino Due.
where,
var= variable
The unsigned int stores the value upto 2 bytes or 16 bits. It stores only positive values. The range of unsigned int data
type is from 0 to 65,535 or 0 to ((2 ^ 16) - 1).
The difference between Unsigned and signed data type is the sign bit. The int type in Arduino is the signed int. In a
16-bit number, 15 bits are interpreted with the 2's complement, while the high bit is interpreted as the positive or
negative number. If the high bit is '1', it is considered as a negative number.
where,
var= variable
For example,
The short is an integer data type that stores two bytes or 16-bit of data.
The range of short data types is from -32768 to 32767 or - (2^ 15) to ((2 ^ 15) - 1). The ARM and ATmega based
Arduino's usually stores the data value of 2 bytes.
where,
var= variable
For example,
1. short pinofLED = 8 ;
The long data types are considered as the extended size variables, which store 4 bytes (32 -bits). The size ranges from
-2,147,483,648 to 2,147,483,647.
While using integer numbers, at least one of the numbers should be followed by L, which forces the number to be a
long data type.
where,
var= variable
For example,
The unsigned long data types are also considered as the extended size variables, which store 4 bytes (32 -bits). It
does not store negative numbers like other unsigned data types, which makes their size ranges from 0 to
4,294,967,295 or (2^32 - 1).
where,
var= variable
For example
byte
1 byte = 8 bits.
where,
var= variable
For example,
1. byte c = 20;
word
It is considered as an unsigned number of 16 bits or 2 bytes, which stores values from 0 to 65535.
where,
var= variable
For example,
1. word c = 2000;
Arduino Variables
The variables are defined as the place to store the data and values. It consists of a name, value, and type.
The variables can belong to any data type such as int, float, char, etc. Consider the url - Arduino data types for
detailed information.
1. int pin = 8;
Here, the int data type is used to create a variable named pin that stores the value 8. It also means that value 8 is
initialized to the variable pin.
We can modify the name of the variable according to our choice. For example,
1. int LEDpin = 8;
For example,
1. pinMode(LEDpin, OUTPUT);
Here, the value stored (8) in the declared variable (LEDpin) will be passed to the pinMode() function.
If we have not declared the variable, the value can also be directly passed to the function.
For example:
1. pinMode( 8, OUTPUT);
Advantages of Variables
o We can easily modify the variables. For example, if we want to change the value of variable LEDpin from 8 to
13, we need to change the only point in the code.
o We can specify any name for a variable. For example, greenpin, bluePIN, REDpin, etc.
1. pin = 7;
We can easily change the variables by copying its value to another variable.
For example,
1. int LEDpin = 7;
3. LEDpin = 13;
The LEDpin now contains the value 13 instead of 7. But, value of pin1 is still 7.
1. void setup()
2. {
3. Serial.begin(9600);
4. int pinLED = 7;
7. pinLED = 13;
10. }
12. {
13. }
Output:
We can notice in the output that the value of LEDpin is changed from 7 to 13. Similarly, we can change the values of
variables.
Variables Scope
The variables can be declared in two ways in Arduino, which are listed below:
o Local variables
o Global variables
Local Variables
The local variables are declared within the function. The variables have scope only within the function. These
variables can be used only by the statements that lie within that function.
For example,
1. void setup()
2. {
3. Serial.begin(9600);
4. }
5. void loop()
6. {
7. int x = 3;
8. int b = 4;
9. int sum = 0;
10. sum = x + b;
11. Serial.println(sum);
12. }
Global Variables
The global variables can be accessed anywhere in the program. The global variable is declared outside the setup()
and loop() function.
For example,
1. int LEDpin = 8;
2. void setup()
3. {
4. pinMode(LEDpin, OUTPUT);
5. }
6. void loop()
7. {
8. digitalWrite(LEDpin, HIGH);
9. }
We can notice that the LEDpin is used both in the loop() and setup() functions.
The value is used in both functions, so, changing the value in one function will reflect in the other. For example,
1. int LEDpin = 8;
2. void setup()
3. {
4. LEDpin = 13;
5. pinMode(LEDpin, OUTPUT);
6. }
7. void loop()
8. {
9. digitalWrite(LEDpin, HIGH);
10. }
The constants in Arduino are defined as the predefined expressions. It makes the code easy to read.
The value of true and false are defined as 1 and 0. Any non-zero integer is determined as true in terms of Boolean
language. The true and false constants are type in lowercase rather than uppercase (such as HIGH, LOW, etc.).
In Arduino, the pin is configured as INPUT or OUTPUT using the pinMode() function. The pin is further made HIGH or
LOW using the digitalWrite() function.
HIGH
The board includes two types of voltage pins to provide HIGH value, which are listed below:
o 5V
o 3V
Some boards consist of both 5V and 3.3V pins. For example, Arduino UNO R3.
LOW
LED_BUILTIN Constant
The Arduino boards have built-in LED connected in series with the resistor. The particular pin number is defined with
the constant name called LED_BUILTIN.
Most Arduino boards have the LED_BUILTIN connected to Pin number 13.
Constant Keyword
The name const represents the constant keyword. It modifies the behavior of the variables in our program. It further
makes the variable as 'read-only'.
The variable will remain the same as other variables, but its value cannot be changed.
It means we cannot modify the constant. For example,
2. //....
The const keyword is considered superior compared to the #define keyword because it obeys the rules of
the variable scope.
For example,
2. float y;
3. void setup()
4. {
5. Serial.begin(9600);
7. Serial.println(y);
8. }
9. void loop()
10. {
11. // ....
Output: 11.36
Note: We can either use const or #define in the case of strings and numeric constants. But we can only use const for
arrays.
#define
The #define in Arduino is used to give a name to the constant value. It does not take any memory space on the chip.
At the compile time, the compiler will replace the predefined value in the program to the constants with the defined
value.
where,
For example,
1. #define LEDpin 12
Note: The #define does not require any semicolon. Hence, we do not need to specify any semicolon after the #define.
Otherwise, the compiler will show errors.
1. #define LEDpin = 12
The operators are widely used in Arduino programming from basics to advanced levels. It plays a crucial role in every
programming concept like C, C++, Java, etc.
The operators are used to solve logical and mathematical problems. For example, to calculate the temperature given
by the sensor based on some analog voltage.
1. Arithmetic Operators
2. Compound Operators
3. Boolean Operators
4. Comparison Operators
5. Bitwise Operators
Arithmetic Operators
There are six basic operators responsible for performing mathematical operations in Arduino, which are listed below:
o Assignment Operator ( = )
The Assignment operator in Arduino is used to set the variable's value. It is quite different from the equal symbol (=)
normally used in mathematics.
o Addition ( + )
The addition operator is used for the addition of two numbers. For example, P + Q.
o Subtraction ( - )
Subtraction is used to subtract one value from the another. For example, P - Q.
o Multiplication ( * )
o Division ( / )
The division is used to determine the result of one number divided with another. For example, P/Q.
o Modulo ( % )
The Modulo operator is used to calculate the remainder after the division of one number by another number.
Most of the operators are similar to the usual operator used in mathematics.
Example 1:
1. int b;
2. void setup ( )
3. {
4. Serial.begin( 9600 );
5. }
6. void loop ( )
7. {
8. b = 5 + 2;
9. Serial.println(b);
10. }
In the above code, we have assigned the result of the addition of two numbers to b before printing it to the console.
For output, click on the Upload and Serial Monitor button present on the toolbar.
Output: 7
Example 2:
1. int d;
2. void setup ( )
3. {
4. Serial.begin( 9600 );
5. }
6. void loop ( )
7. {
8. d = 5 - 2;
9. Serial.println(d);
10. d = d + 3;
11. Serial.println(d);
12. }
Here, d= d +3 is not operated as a usual mathematical operation. It is the assignment operator where right of the
function is evaluated first and is assigned to the left of the equal sign.
Similarly, we can perform multiplication, modulo, and division. The int variable will store the integer values. For
example, 20/3 = 6.
If we want decimal values to be printed, we need to use the float instead of int.
For example,
1. int b;
2. void setup ( )
3. {
4. Serial.begin( 9600 );
5. }
6. void loop ( )
7. {
8. b = 20.0 / 3; // decimal value is used to force the compiler to print decimal value.
9. Serial.println(b);
10. }
Output: 6.66
Let's understand the order of operations considered by the Arduino while performing calculation:
1. Parentheses ( )
If there are multiple operations next to each other, they will be computed from left to right.
Let's understand with an example.
1. int c;
2. void setup ( )
3. {
4. Serial.begin( 9600 );
5. }
6. void loop ( )
7. {
8. c = 2 * 3 / (2 + 1) + 4;
9. Serial.println(c);
10. }
Output:
Let's understand how the above output occurred. Consider the below image:
Compound Operators
The result of the right operand is assigned to the left operand, as already discussed above. The same condition will
apply to all the compound operators, which are listed below:
o b++
Here, b = b + 1. It is called the increment operator.
o b+=
o b--
o b-=
o b*=
o b/=
o b%=
Now, let's use the above operators with two variables, b and c.
o b + = c ( b = b + c)
o b - = c ( b = b - c)
o b * = c ( b = b * c)
o b / = c ( b = b / c)
o b % = c ( b = b % c)
Boolean Operators
The Boolean Operators are NOT ( ! ), Logical AND ( & & ), and Logical OR ( | | ).
The result of the condition is true if both the operands in the condition are true.
1. if ( a = = b & & b = = c )
Above statement is true if both conditions are true. If any of the conditions is false, the statement will be false.
o Logical OR ( | | )
The result of the condition is true, if either of the variables in the condition is true.
1. if ( a > 0 | | b > 0 )
The above statement is true, if either of the above condition ( a> 0 or b > 0 ) is true.
o NOT ( ! )
For example, a ! = 2.
The NOT operator returns the value 1 or TRUE when the specified operand is FALSE. It also reverses the value of the
specified expression.
Comparison Operators
The comparison operators are used to compare the value of one variable with the other.
The less than operator checks that the value of the left operand is less than the right operand. The statement is true
if the condition is satisfied.
1. int b;
2. int c ;
3. void setup ( )
4. {
5. Serial.begin( 9600 );
6. }
7. void loop ( )
8. {
9. b = 3;
10. c = 5;
11. if ( b < 4 )
12. Serial.println(b);
13. if ( c < 4)
15. }
Output: 3
In the above code, if any of the two statement is correct, the corresponding value of the variable will be printed.
Here, only first condition is correct. Hence, the value of b will be printed.
The less than operator checks that the value of the left side of a statement is greater than the right side. The
statement is true if the condition is satisfied.
o equal to ( = = )
It checks the value of two operands. If the values are equal, the condition is satisfied.
For example, a = = b.
o not equal to ( ! = )
It checks the value of two specified variables. If the values are not equal, the condition will be correct and satisfied.
For example, a ! = b.
The less or equal than operator checks that the value of left side of a statement is less or equal to the value on right
side. The statement is true if either of the condition is satisfied.
The greater or equal than operator checks that the value of the left side of a statement is greater or equal to the
value on the right side of that statement. The statement is true if the condition is satisfied.
It checks the value of a is greater or equal than b. If either of the condition satisfies, the statement is true.
Bitwise Operators
The Bitwise operators operate at the binary level. These operators are quite easy to use.
There are various bitwise operators. Some of the popular operators are listed below:
o bitwise NOT ( ~ )
The bitwise NOT operator acts as a complement for reversing the bits.
o bitwise XOR ( ^ )
The output is 0 if both the inputs are same, and it is 1 if the two input bits are different.
For example,
For example,
1. 1 0 0 1 // input 1 or operand 1
2. 0 1 0 1 // input 2
o bitwise OR ( | )
The output is 0 if both of the inputs in the OR operation are 0. Otherwise, the output is 1. The two input patterns are
of 4 bits.
For example,
1. 1 1 0 0 // input 1 or operand 1
2. 0 0 0 1 // input 2
The output is 1 if both the inputs in the AND operation are 1. Otherwise, the output is 0. The two input patterns are
of 4 bits.
For example,
1. 1 1 0 0 // input 1 or operand 1
2. 0 1 0 1 // input 2
The left operator is shifted by the number of bits defined by the right operator.
The right operator is shifted by the number of bits defined by the left operator.
Arduino Array
The arrays are defined as the data structures that allow multiple values to be grouped together in a simple way. This
is an easily access method.
The array is normally built from the data types like integer, reals, characters, and boolean. It refers to a named list of
finite number (n) of similar data elements.
The set of consecutive numbers usually represent the elements in the array, which are 0, 1, 2, 3, 4, 5, 6,.......n.
For example, if the name of an array of 5 elements is AR, the elements will be referenced as shown below:
Arrays in Arduino
It is also defined as the collection of variables, which is acquired with an index number.
We can specify any name according to our choice. The array name is the individual name of an element.
Array Declaration
There are different methods to declare an array in Arduino, which are listed below:
For example,
1. int myarray[ ] = { 1, 4, 6, 7 } ;
For example,
Features of Array
o The size of the array should not be less than the number of elements. For example,
o The total elements, while specifying the char type should be (n - 1), where n is the size of the array. It is
because one element is required to hold the null character in the array.
For example,
Let's specify the array as char abc[8 ] = " Arduino";
The array in Arduino has zero index. It means that the first element of the array is indexed as 0. For example,
1. myvalue[0] = = 1, myvalue[1] = = 2, . . . .
Example 1:
Let's take an array (ARarduino) of 6 elements. The elements of the array are shown below:
and ARarduino[5].
The last element of the array will be n-1, where n is the declared size of an array.
4. //ARarduino[6] is invalid
Let's consider an array (AR) with 4 elements. The elements are: AR[0], AR[1], AR[2], and AR[3].
The sum of values assigned to the elements within an array will be printed.
Example 2: Division
We will divide the value assigned to the element AR[4] with 2. The resulting value will be assigned to the variable 'z.'
Consider the below code:
1. z = AR[4] / 2;
2. Serial.println ( x );
We need to be careful while assigning value to the array. The index number greater than the size of the array may
yield invalid data. Such data is saved to random memory locations, which can cause the program malfunction or a
difficult bug to find.
Note: C++ does not check the legally bound size of the declared array, while JAVA and BASIC do check.
1. myArray[0] = 5;
Example of project: We will also discuss a project to light LED using arrays in the Basic projects -> Blinking various
LEDs using Arrays.
Loop Arrays
We can also use arrays inside the loop. For each element of an array, the loop counter acts as an index element for
that array.
In this example, the element over the serial port will be printed.
2. {
3. Serial.println(myArray[i]);
4. }
Code Examples
2. int b[sizeOFarray] = {10, 20, 30, 40, 50}; // five values initialized to five elements of an array
3. int sum = 0;
4.
5. void setup ()
6. {
7. Serial.begin(9600);
8. }
9. void loop ()
10. {
16. }
Output
In the above code, we have used the const variable. The compiler reserves the memory in Arduino. We need to use
the const integer greater than zero. For detail- go to the URL Arduino Variables.
2. int b[sizeOFarray] = {10, 30, 40, 55, 65}; // five values initialized to five elements of an array
3. int sum = 0;
4. int average = 0;
5.
6. void setup ()
7. {
8. Serial.begin(9600);
9. }
18. }
Output
40
Arduino Delay
Here, Arduino Delay specifies the delay( ) function used in the Arduino programming. Let's discuss the delay( )
function in detail.
delay( ) function
The delay( ) function pauses the program or task for a specified duration of time. The time is specified inside the
open and closed parentheses in milliseconds.
Where,
Example 1:
delay(500)
It is shown below:
The program waits for a specified duration before proceeding onto the next line of the code. The delay( ) function
allows the unsigned long data type in the code.
We can create many sketches using the short and long delays depending on the requirements in the project. It does
not disable any interrupts. But, the delay( ) function has some drawbacks.
The delay( ) cease (stops) the other activities, such as manipulation of pins on the board, mathematical calculations,
reading of other sensors during the delay function. The programmers usually avoid delay( ) of more than 10 seconds
in the sketch.
Let's understand the delay() function with the help of two examples.
Example 1:
4. void setup( )
5. {
6. pinMode( LEDlightPin, OUTPUT) // the digital pin on board is set as the Output.
7. }
8. void loop( )
9. {
11. delay(1500); // The LED will light/ON for 1.5 seconds = 1500 milliseconds
13. delay(500); // The LED will dim/OFF for 0.5 seconds = 0.5x1000 = 500 milliseconds
15. }
Example 2:
1. void setup ( )
2. {
3. Serial.begin ( 4800); //opens the serial port and set the bits per rate to 4800
4. }
5. void loop ( )
6. {
7. Serial.print(" Welcome");
8. delay(1000);
10. delay ( 500); // delay of 0.5 seconds between each printed line.
11. }
In the output, the word Welcome will appear followed by the word to delay 1 second later. After 0.5 seconds,
another line will be printed.
Output:
Welcome to delay
Welcome to delay
The if ( ) statement is the conditional statement, which is the basis for all types of programming languages.
If the condition in the code is true, the corresponding task or function is performed accordingly. It returns one value
if the condition in a program is true. It further returns another value if the condition is false.
It means that if ( ) statement checks for the condition and then executes a statement or a set of statements.
It clearly explains the process of execution of a statement. If the condition is False, it comes out of the if ( )
statement. If the condition is true, the function is performed.
1. if ( condition)
2. {
3. // include statements
5. // then performs the function or task specified inside the curly braces
6. }
Here,
The comparison operators that can be used as a condition inside the parentheses are listed below:
o a ! = b ( a not equal to b )
o a = = b ( a equal to b )
where,
Code Examples
Example 1:
2. int b = 4;
3. void setup()
4. {
5. Serial.begin(9600);
6. }
7. void loop()
8. {
9. if (a > b )
10. {
12. }
13. if (b > a )
14. {
16. }
17. }
The code shows the initialization of values to the two variables a and b. In this example, the first condition is True.
Hence the corresponding information is printed.
Example 2:
3. int x = 80 ;
4. void setup ( )
5. {
6. Serial.begin( 9600 );
9. }
11. {
13. {
16. }
18. {
21. }
22. }
In the above example, we have initialized the value of x. Since the value of x is less than 100, the second condition is
true. Hence, LED2 will light up.
The else and else-if both are used after specifying the if statement. It allows multiple conditions to be grouped.
If else
The if-else condition includes if ( ) statement and else ( ) statement. The condition in the else statement is executed if
the result of the If ( ) statement is false.
1. if (condition)
2. {
3. // statements
4. }
5. else
6. {
7. //statements
8. }
The else( ) statement can also include other if statements. Due to this, we can run multiple statements in a single
program.
Code Example
Example 1:
1. int a = 5;
2. int b= 6;
3. void setup ( )
4. {
5. Serial.begin ( 9600 );
6. }
7. void loop ( )
8. {
9. if ( a > b )
10. {
12. }
13. else
14. {
16. }
17. }
In the above example, the values are initialized to the variables a and b. The message concerning the satisfied
condition will be printed.
Example 2:
2. int x = 150 ;
3. void setup ( )
4. {
5. Serial.begin( 9600 );
7. }
8. void loop ( )
9. {
11. {
15. }
16. else
17. {
19. }
20. }
Output: LED1 will light +++
If the initialized value of x is less than 100, the message ' LED1 will not light ' will be printed in the output.
Else if
The else if statement can be used with or without the else ( ) statement. We can include multiple else if statements in
a program.
1. if (condition)
2. {
3. // statements
4. }
5. else if ( condition)
6. {
7. // statements
9. }
10. else
11. {
12. //statements
13. }
Code Example
Example 1:
1. int i = 2;
2. int j = 3;
3. void setup ( )
4. {
5. Serial.begin(9600);
6. }
7. void loop ( )
8. {
9. if ( i > j )
10. {
12. }
14. {
16. }
17. else
18. {
20. }
21. }
Output: J is greater
The else if ( ) statement will stop the flow once its execution is true.
The Else ( ) part is executed if one or all the If ( ) conditions present in the code comes out to be false.
The statements inside the curly brackets under for loop are executed repeatedly according to the specified condition.
An increment counter in the for loop is used to increment or decrement the loop repetitions.
The for statement is commonly used for repetitive task or operation or to operate on the group of data/pins in
combination with arrays.
2. {
3. \\ statements
4. }
where,
o condition: The condition is tested on every execution. If the condition is true, it will execute the given task.
The loop ends only when the condition becomes false.
o increment: It includes the increment operator, such as i + +, i - - , i + 1, etc. It is incremented each time until
the condition remains true.
For example,
1. for ( i = 0 ; i < 5 ; i + +)
The above statement will execute the loop for five times. The values of i will be from 0 to 4.
1. for ( i = 0 ; i < = 5 ; i + +)
The above statement will execute the loop six times. The values of i will be from 0 to 5.
Note: If we do not want to execute the for loop again and again. Then, we can insert the for loop in the void setup( )
function.
Example 1:
To overcome this, programmers prefer to use for loop to execute a task multiple times, while using a single
statement.
1. int i;
2. void setup ( )
3. {
4. Serial.begin(9600);
5. for ( i = 0 ; i < 15 ; i ++ )
6. {
7. Serial.println( "Arduino");
8. }
9. }
11. }
Output:
Example 2:
The multiplication increment in the for loop will generate a logarithmic progression.
1. int x;
2. void setup ( )
3. {
4. Serial.begin(9600);
6. {
7. Serial.println(x);
8. }
9. }
11. }
Output:
We can also declare the int data type directly in the for loop.
For example,
Here, fade and LED means that LED will faint slowly.
1. const int pinPWM = 11; // here, we have initialized the PWM pin.
2. void setup ( )
3. {
4. Serial.begin(9600);
5. }
6. void loop ( )
7. {
8. int x = 1;
10. {
12. if (i == 255)
13. {
15. }
17. // the lesser the time, the more fading effect can be seen clearly
18. }
19. }
For the connection, we will connect the positive terminal of the LED in series with the resistor to PIN 11 (PWM pin),
and the negative terminal of the LED to GND.
Note: The for loops in C++ programming language is much more flexible than other types of programming languages.
Example 4:
1. void setup ( )
2. {
3. int i;
4. Serial.begin(9600);
5. for (i = 0; i < 4; i = i + 1)
6. {
8. }
10. }
12. {
13. }
The above code will print 'Hello Arduino' four times. After that the condition becomes false, control comes out of the
loop, and 'DONE' is printed.
Output:
The while loop() is the conditional loop that continues to execute the code inside the parentheses until the specified
condition becomes false.
The while loop will never exit until the tested condition is changed or made to stop. The common use of a while loop
in Arduino includes sensor testing, calibration (calibrating the input of sensor), variable increment, etc.
1. while (condition)
2. {
4. }
where,
condition: It specifies the boolean expression, which determines the condition to be true or false.
For example,
1. variable = 0;
5. }
The above code inside the curly braces in while loop will execute continuously and repeatedly as long as the variable
is less than 100.
Flowchart
In order to change the flow of the program, we need to change the specified condition inside the parentheses of
while loop. The process is much like the if statement.
ADVERTISING
Example 1:
1. int a = 0;
2. void setup()
3. {
4. Serial.begin(9600);
5. while( a < 5)
6. {
7. Serial.println("Welcome to Arduino");
8. a = a + 1;
9. }
10. }
12. {
13. }
Output:
The message inside the loop will be printed five times, as shown below:
Explanation: At first, we have defined the variable a as 0, and initialized the serial monitor as usual (means
Serial.begin()). The loop first checks the condition specified within the parentheses. At first, a =0. The condition is
true (0 < 5). The code inside the curly braces will execute, and the message is printed.
Now, the value of a is incremented (added 1 to a), and the loop executes again.
Similarly, five times the condition remains true. When a =5, the condition becomes false, and the loop exits and
drops. The code outside the loop is executed.
Example 2:
The code is similar to the above example. We will only add some statements outside the loop.
1. int a = 0;
2. void setup()
3. {
4. Serial.begin(9600);
5. while( a < 5)
6. {
7. Serial.println("Welcome to Arduino");
8. a = a + 1;
9. }
10. Serial.println("DONE");
12. }
14. {
15. }
Output:
We can notice that as soon as the condition in the loop becomes false, the message specified outside the loop is
printed.
do...while
The working of the do-while loop is similar to the while loop. The condition inside the do-while will execute at least
once. It is because the condition is tested at the end of the loop instead of the beginning.
1. do
2. {
4. } while (condition);
where,
condition: It specifies the boolean expression, which determines the condition to be true or false.
For example,
1. int b = 0;
2. do {
Flowchart
Code Example
Example 1:
Consider the below code:
1. int a = 0;
2. void setup()
3. {
4. Serial.begin(9600);
5. do
6. {
8. a = a + 1;
10. }
12. {
13. }
Output:
Arduino switch case
The switch case controls the flow of the program by executing the code in various cases. A switch statement
compares a particular value of a variable with statements in other cases. When the statements in a case matches the
value of a variable, the code associated with that case executes.
The break keyword is used at the end of each case. For example, if there are five cases, the break statements will also
be five. The break statement exits the switch case.
The switch statement without a break will continue to execute all the cases until the end. Hence, it is essential to
include a break statement at the end of each case.
1. switch(variable)
2. {
3. case 1:
5. break;
6. case 2:
8. break;
9. .
10. .
11. case n:
13. break;
14. default:
16. //if nothing matches in the above cases, the default statement runs
17. break;
18. }
where,
variable: It includes the variables whose value will be compared with the multiple cases
value: It consists of a value to compare. These values are constants. The allowed data types are int and char.
Yes.
But for some cases, implementing a switch case is somewhat easier than if statements.
It is recommended to use switch cases instead of if statement when multiple conditions of a non-trivial expression
are being compared.
The if statement allows us to choose between the two options, TRUE or FALSE. We can also use multiple if
statements for more than two cases. The switch case allows us to choose between various discrete options.
Code Example
We will include the switch case in the setup() function, as we do not require the repeated execution.
2. void setup()
3. {
4. Serial.begin(9600);
5. int a = 1;
6. switch(a) // the case matching the value in the declared variable will run
7. {
8. case 1:
12. break;
13. case 2:
15. break;
16. case 3:
18. break;
19. default:
21. break;
22. }
23. }
25. {
26. }
Output:
Arduino String
The string is a data type that stores text rather than the integer values. It is similar to other data types such as
integer, float, etc., in Arduino.
The string is an array of characters or a set of characters that consists of numbers, spaces, and special
characters from the ASCII table.
o char StrA[10];
o char StringB[8] = {'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
We can also declare an array with extra space for a string constant StrA.
The data type is char. Each character is an element in string. For example, Arduino contains seven characters. So, we
need to declare an array atleast of size 8 (1 extra to store the null character at the end of the string).
When we create a string using the double quotes like the word "text" specified above, the compiler automatically
creates an element out of each character. It further appends the null character to the end.
The null character has the value 0 in the ASCII table. It is defined using two characters ( \ and \0). The backslash (\)
represents the special character when used in conjunction with other characters. The backslash is also known as
an escape character. The null character is added by the compiler to terminate the string.
Note: Strings are always declared inside the double quotes, while characters are declared inside single quotes.
It is interesting to know how print() and println() function works with the strings.
Let's start.
4. void setup()
5. {
6. Serial.begin(9600);
7. }
8. void loop()
9. {
11. {
14. {
15. break; //
16. }
17. Serial.print(myString[i]);
18. }
19. Serial.println();
20. delay(500);
21. }
The code will print Hello Arduino multiple times, as shown below:
In the case of println() function, we need not require any for loop or condition to print.
3. void setup()
4. {
5. Serial.begin(9600);
6. }
7. void loop()
8. {
9. Serial.println(myString);
10. delay(500);
11. }
Output:
Array of Strings
We can specify the array of strings while working with large projects, such as LCD display, etc.
The array names are also considered as pointers. The data type marked with an asterisk is defined as pointers.
1. char *StrAB[] = {"Welcome to string A to G in Arduino", "Here is string A", "Here is string B", "Here is string C
", "Here is string D", "Here is string E",
3. void setup() {
4. Serial.begin(9600);
5. }
6. void loop() {
8. {
9. Serial.println(StrAB[i]);
10. delay(1000);
11. }
12. }
Output:
Arduino String Object
An object is like a variable, which points to a memory location that holds some data. The functions associated with
the object are called member functions. As a result, we can make the objects to perform some actions.
For example,
The begin(), print(), and println() are the functions that are declared using the serial object. The period after the
Serial (print(), etc.) specifies that we are accessing some members within the serial object. The members can be
either a function or a variable.
The parentheses after the print() and println() function determines the function being called in the serial. These
functions cannot be declared alone in the global scope in the code. Thus, they are declared with the serial object as
Serial.print() and Serial.println().
String Object
The String object allows us to store and perform actions on an array of characters. The String object takes more
memory than the regular String.
The String object is always displayed with the uppercase 'S'. It produces an instance of the String class.
It can be constructed from different data types, which are listed below:
The specified number in a string has a default base of 10. For example,
It creates a string that consists of the ASCII representation of the number 15.
To specify a number with base other than 10, the String can be created as:
It will give us the String ''F''. It signifies the hexadecimal conversion of the decimal number 15.
It will give us the String ''1111''. It signifies the hexadecimal conversion of the decimal number 15.
1. String(value)
2. String(value, base)
3. String(value, PlacesofaDecimal)
where,
The data types are byte, unsigned int, char, float, double, unsigned long, long, int, and string.
base: It signifies the base, which is required to format the integer value. For example, HEX, BIN, etc.
PlacesofaDecimal: It specifies the desired decimal places, which is only needed if the value is double or float.
o charAT()
1. thisString.charAT(n)
where,
n is also a variable
The above syntax will return the nth character of the specified string.
o compareTo()
It is used to compare the two Strings. The specified Strings are compared using the ASCII values of the characters.
1. thisString.compareTo(myString)
where,
The above syntax will return a negative number if thisString comes before myString.
o endsWith()
It tests that if a String ends with the characters of other String or not.
where,
It will return true if thisString ends with the characters of myString. Otherwise, it will return false.
o startsWith()
It tests that if a String starts with the characters of other String or not.
1. thisString.startsWith(myString)
where,
It will return true if thisString starts with the characters of myString. Otherwise, it will return false.
o toLowerCase()
1. thisString.toLowerCase()
where,
o toUpperCase()
1. thisString.toUpperCase()
where,
o equals()
It compares the equality of the Two Strings. The comparison is quite sensitive, where String "Arduino" is not equal to
the String "ARDUINO".
1. thisString.equals(myString)
where,
It will return true if thisString equals to myString. Otherwise, it will return false.
o getBytes()
It copies the characters of the String to the supplied buffer.
1. thisString.getBytes(buffer, length)
where,
buffer: The characters are copied into the buffer. The required data type is the byte.
length: It signifies the size of the buffer. The required data type is unsigned int.
o lastIndexOf()
1. thisString.lastIndexOf(value)
2. thisString.lastIndexOf(value, from)
where,
value: It includes the particular value to search for. The required data types are String and char.
o substring()
1. thisString.substring(from)
2. thisString.substring(from, to)
where,
from: It is defined as the index, from where the substring will start
o toInt()
1. thisString.toInt()
where,
The required data type is long. It returns zero if the conversation is invalid or a String does not start with an integer
number.
o toFloat()
1. thisString.toFloat()
where,
The required data type is float. It returns zero if the conversation is invalid or a String does not start with a digit.
o trim()
1. thisString.trim()
where,
Code Example
Example 1:
1. void setup()
2. {
3. Serial.begin(9600);
5. Serial.println(thisString.charAt(8));
6. }
7. void loop()
8. {
9. }
Output: t
Example 2:
2. {
3. Serial.begin(9600);
5.
6. thisString.concat("String Object");
7.
8. Serial.println(thisString);
9. }
11. {
12. }
Output