0% found this document useful (0 votes)
11 views35 pages

IOT-UNIT IV - Programming The Arduino

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views35 pages

IOT-UNIT IV - Programming The Arduino

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

VISION INSTITUTE OF TECHNOLOGY, Internet Of Things

ALIGARH SUBJECT CODE: BCS 070

UNIT- IV
Programming The Arduino

What is Arduino?

Arduino is an open-source electronics platform used to build interactive electronic projects. It


consists of two main parts:

1. Hardware (Arduino Boards)


These are small microcontroller boards such as:

 Arduino Uno (most common for beginners)


 Arduino Mega
 Arduino Nano
 Arduino Leonardo
 etc.

They include:

 A microcontroller (like ATmega328P)


 Digital & analog input/output pins
 USB port for programming
 Power connectors

2. Software (Arduino IDE)


A free application where you write code (called sketches) in a language similar to C/C++.
The IDE uploads the code to the Arduino board.

What Arduino Can Do


Arduino is used to control sensors, motors, LEDs, displays, and more. Common applications:

 Robotics
 Home automation
 IoT projects
 Sensor monitoring (temperature, gas, humidity, etc.)
 Mini-projects for engineering students

Why Arduino Is Popular

 Easy for beginners


 Huge community support
1 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

 Low cost
 Lots of libraries and sample codes
 Works on Windows, Mac, Linux

Arduino Platform Boards – Anatomy:


Although different Arduino boards (Uno, Mega, Nano, etc.) vary in size, most follow the same
basic structure. Below is the anatomy using Arduino Uno as the reference, since it’s the most
widely used.

1. USB Connector

 Used to upload code from the computer to the board.


 Also provides power when connected to a PC.

2. Power Jack (DC Barrel Jack)

 To power the board using an external adapter (7–12V recommended).

3. Voltage Regulator

 Ensures the board receives stable 5V or 3.3V.


 Protects the board from voltage fluctuations.

4. Microcontroller (ATmega328P in Arduino Uno)

This is the brain of the Arduino.


It:

 Executes your code


 Reads inputs (sensors)
 Controls outputs (LEDs, motors)

5. Crystal Oscillator

 Provides a clock signal (usually 16 MHz) to keep timing accurate.

6. Reset Button

 Restarts the program running on the Arduino.


 Useful during testing/debugging.

2 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

7. Power Pins

These pins supply power to components:

 5V – regulated 5 volt output


 3.3V – regulated 3.3 volt output
 GND – ground
 VIN – connect external power supply here

8. Digital I/O Pins

 Located on the top of the board (0–13 on Uno)


 Used to read or send digital signals: HIGH (1) or LOW (0)

Some special digital pins:

 PWM Pins (~ symbol) – simulate analog output


 UART Serial Pins (0,1) – TX/RX for communication

9. Analog Input Pins

 Labeled A0–A5
 Used to read analog signals from sensors (0–1023 values)

10. ICSP Header

Used for:

 Programming the microcontroller directly


 Connecting external programmers or shields

11. Power LED Indicator

 A small LED marked ON


 Lights up when the board is powered.

12. Built-in LED

 Connected to pin 13
 Useful for beginner testing (e.g., blink program)

3 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

13. TX & RX LEDs

 Blink when the Arduino sends (TX) or receives (RX) serial data.

14. Reset Header

 Another reset pin for shields or external devices.

Arduino Board Anatomy:

4 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
Power USB
Arduino board can be powered by using the USB cable from your computer. All you
need to do is connect the USB cable to the USB connection (1).

Power (Barrel Jack)


Arduino boards can be powered directly from the AC mains power supply by connecting
it to the Barrel Jack (2).

Voltage Regulator
The function of the voltage regulator is to control the voltage given to the Arduino board
and stabilize the DC voltages used by the processor and other elements.

Crystal Oscillator
The crystal oscillator helps Arduino in dealing with time issues. How does Arduino
calculate time? The answer is, by using the crystal oscillator. The number printed on top
of the Arduino crystal is 16.000H9H. It tells us that the frequency is 16,000,000 Hertz or
16 MHz.

Arduino Reset
You can reset your Arduino board, i.e., start your program from the beginning. You can
reset the UNO board in two ways. First, by using the reset button (17) on the board.
Second, you can connect an external reset button to the Arduino pin labelled RESET (5).

Pins (3.3, 5, GND, Vin)


 3.3V (6) − Supply 3.3 output volt
 5V (7) − Supply 5 output volt
 Most of the components used with Arduino board works fine with 3.3 volt and 5
volt.
 GND (8)(Ground) − There are several GND pins on the Arduino, any of which can
be used to ground your circuit.
 Vin (9) − This pin also can be used to power the Arduino board from an external
power source, like AC mains power supply.

Analog pins
The Arduino UNO board has six analog input pins A0 through A5. These pins can read
the signal from an analog sensor like the humidity sensor or temperature sensor and
convert it into a digital value that can be read by the microprocessor.

Main microcontroller
Each Arduino board has its own microcontroller (11). You can assume it as the brain of
your board. The main IC (integrated circuit) on the Arduino is slightly different from
board to board. The microcontrollers are usually of the ATMEL Company. You must
know what IC your board has before loading up a new program from the Arduino IDE.
This information is available on the top of the IC. For more details about the IC
construction and functions, you can refer to the data sheet.

5 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
ICSP pin
Mostly, ICSP (12) is an AVR, a tiny programming header for the Arduino consisting of
MOSI, MISO, SCK, RESET, VCC, and GND. It is often referred to as an SPI (Serial
Peripheral Interface), which could be considered as an "expansion" of the output.
Actually, you are slaving the output device to the master of the SPI bus.

Power LED indicator


This LED should light up when you plug your Arduino into a power source to indicate
that your board is powered up correctly. If this light does not turn on, then there is
something wrong with the connection.

TX and RX LEDs
On your board, you will find two labels: TX (transmit) and RX (receive). They appear in
two places on the Arduino UNO board. First, at the digital pins 0 and 1, to indicate the
pins responsible for serial communication. Second, the TX and RX led (13). The TX led
flashes with different speed while sending the serial data. The speed of flashing depends
on the baud rate used by the board. RX flashes during the receiving process.

Digital I/O
The Arduino UNO board has 14 digital I/O pins (15) (of which 6 provide PWM (Pulse
Width Modulation) output. These pins can be configured to work as input digital pins to
read logic values (0 or 1) or as digital output pins to drive different modules like LEDs,
relays, etc. The pins labeled ~ can be used to generate PWM.

AREF
AREF stands for Analog Reference. It is sometimes, used to set an external reference
voltage (between 0 and 5 Volts) as the upper limit for the analog input pins.

ARDUINO IDE:

In this section, we will learn in easy steps, how to set up the Arduino IDE on our computer and
prepare the board to receive the program via USB cable.

Step 1 − First you must have your Arduino board (you can choose your favorite board) and a USB
cable. In case you use Arduino UNO, Arduino Duemilanove, Nano, Arduino Mega 2560, or
Diecimila, you will need a standard USB cable (A plug to B plug), the kind you would connect to a
USB printer as shown in the following image.

6 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

In case you use Arduino Nano, you will need an A to Mini-B cable instead as shown in the
following image.

Step 2 − Download Arduino IDE Software.

You can get different versions of Arduino IDE from the Download page on the Arduino Official
website. You must select your software, which is compatible with your operating system
(Windows, IOS, or Linux). After your file download is complete, unzip the file.

7 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

Step 3 − Power up your board.

The Arduino Uno, Mega, Duemilanove and Arduino Nano automatically draw power from either,
the USB connection to the computer or an external power supply. If you are using an Arduino
Diecimila, you have to make sure that the board is configured to draw power from the USB
connection. The power source is selected with a jumper, a small piece of plastic that fits onto
two of the three pins between the USB and power jacks. Check that it is on the two pins closest
to the USB port.

Connect the Arduino board to your computer using the USB cable. The green power LED (labeled
PWR) should glow.

Step 4 − Launch Arduino IDE.

After your Arduino IDE software is downloaded, you need to unzip the folder. Inside the folder,
you can find the application icon with an infinity label (application.exe). Double-click the icon to
start the IDE.

Step 5 − Open your first project.

Once the software starts, you have two options −

 Create a new project.


 Open an existing project example.

8 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
To create a new project, select File → New.

To open an existing project example, select File → Example → Basics → Blink.

9 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
Here, we are selecting just one of the examples with the name Blink. It turns the LED on and off
with some time delay. You can select any other example from the list.

Step 6 − Select your Arduino board.

To avoid any error while uploading your program to the board, you must select the correct
Arduino board name, which matches with the board connected to your computer.

Go to Tools → Board and select your board.

Here, we have selected Arduino Uno board according to our tutorial, but you must select the
name matching the board that you are using.

Step 7 − Select your serial port.

10 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
Select the serial device of the Arduino board. Go to Tools → Serial Port menu. This is likely to be
COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out,
you can disconnect your Arduino board and re-open the menu, the entry that disappears should
be of the Arduino board. Reconnect the board and select that serial port.

Step 8 − Upload the program to your board.

Before explaining how we can upload our program to the board, we must demonstrate the
function of each symbol appearing in the Arduino IDE toolbar.

11 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

A − Used to check if there is any compilation error.

B − Used to upload a program to the Arduino board.

C − Shortcut used to create a new sketch.

D − Used to directly open one of the example sketch.

E − Used to save your sketch.

F − Serial monitor used to receive serial data from the board and send the serial data to the
board.

Now, simply click the "Upload" button in the environment. Wait a few seconds; you will see the
RX and TX LEDs on the board, flashing. If the upload is successful, the message "Done uploading"
will appear in the status bar.

Note − If you have an Arduino Mini, NG, or other board, you need to press the reset button
physically on the board, immediately before clicking the upload button on the Arduino Software.

What is IDE (Integrated Development Environment)?


An IDE (Integrated Development Environment) is software that combines commonly used
developer tools into a compact GUI (graphical user interface) application. It is a combination of
tools like a code editor, code compiler, and code debugger with an integrated terminal.

Integrating features like software editing, building, testing, and packaging in a simple-to-use
tool, IDEs help boost developer productivity. IDEs are commonly used by programmers and
software developers to make their programming journey smoother.

Why are IDEs important?


One certainly does not need an IDE to code or develop applications. Even a simple text editor
like notepad can be used to write code. However, IDEs offer some stunning features that go
beyond ordinary editing. By providing frequently used developer tools all in one simple
12 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

interface, one can directly get on to building their applications without going through the
hardship of manually configuring and integrating the development environment.

Common Features of an IDE (Integrated Development Environment)


IDEs provide a broad variety of features which typically consist of:
 Editor: Typically, a text editor can help you write software code by highlighting syntax with
visual cues, providing language-specific auto-completion, and checking for bugs as you
type.
 Compiler: A compiler interprets human-readable code into machine-specific code that can
be executed on different operating systems like Linux, Windows, or Mac OS. Most
IDEs usually come with built-in compilers for the language it supports.
 Debugger: A tool that can assist developers to test and debug their applications and
graphically point out the locations of bugs or errors if any.
 Build-in Terminal: Terminal is a text-based interface that can be used for interacting with
the machine's operating system. Developers can directly run the scripts or commands
within an IDE with a built-in terminal/console.
 Version Control: Version control helps bring clarity to the development of the
software. Some IDEs also support version control tools like Git, through which a user can
track and manage the changes to the software code.
 Code snippets: IDEs support code snippets that are usually used to accomplish a single task
and can also reduce redundant work to some great extent.
 Extensions and Plugins: Extensions and Plugins are used to extend the functionality of the
IDEs with respect to specific programming languages.
 Code navigation: IDEs come with tools like code folding, class and method navigation, and
refactoring tools that make it simple to go through and analyze code.

Why do Developers Use IDE (Integrated Development Environment)?


By providing a single, unified environment for managing all aspects of the development
process, IDEs can help improve a developer's productivity, code quality, and overall
development experience.
 Productivity: By combining common activities such as editing code, building executables,
debugging, and testing as part of software/application development, IDEs help by reducing
time and increasing overall productivity.
 Code Quality: IDEs come with built-in tools as a part of a single GUI, through which
developers can execute actions without switching between applications. Furthermore, it
can also help in Syntax highlighting, code refactoring, and code analysis boosting
overall code quality.
 Integrated Environment: IDEs come pre-built with a combination of development tools that
allow developers to start programming new applications quickly. With IDEs, it is no longer
necessary to manually configure and integrate numerous utilities as part of the setup
procedure. Additionally, since every utility is available on the same workbench, developers
don't have to spend hours learning how to use each one separately.
 Customizability: By incorporating customization options ranging from custom color
schemes, and keyboard shortcuts, to choosing unique layouts, different plugins, and add-
ons; IDEs enable developers to customize their environment to their unique needs and
tastes, improving the comfort and efficiency of the development process.

13 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

Types of IDEs:
IDEs come in various forms, some are designed to work for a specific language whereas some
are targeted to a particular platform like mobile devices. Hence, it becomes equally
important to choose an IDE best suited to one's needs.
1. Desktop IDEs
This type includes the IDEs that can be configured locally. They do not need an active internet
connection to build/run programs. Desktop IDEs are highly customizable to suit developer-
specific needs and provide performance irrespective of the internet
speed. Examples: include Microsoft Visual Studio, Eclipse, Netbeans, etc.
2. Cloud IDEs
Cloud IDEs eliminate the overhead of configuring the software locally. They run on
remote servers and can be accessed through desktop browsers. Cloud IDEs provide better
accessibility and platform independence making them accessible through the Internet
Irrespective of the Client Operating System. Cloud IDEs can be used freely or can have pricing
models with respect to the provider. Examples: Include Gitpod, AWS Cloud 9, Replit, etc.
3. Mobile App Development IDEs
These IDEs are specially designed for creating mobile applications. They include features like
Emulator support and integration for developing and testing mobile applications. Mobile
Development IDEs can be in the form of Desktop IDE or Cloud IDE. Examples: Include Android
Studio, Flutlab.io, etc.
4. Database-Specific IDEs
These IDEs (Integrated Development Environments) are specially designed for working with
databases. They include features like query builders and n for developing and testing mobile
applications. Like mobile-development IDEs, Database IDEs can also be in the form of Desktop
IDE or Cloud IDEs. Examples: Include MySQL Workbench, Oracle SQL Developer, etc.

How Should I Choose an IDE?


One can find many IDEs available in the market, while some are open-source and free to use,
others may work with subscription models. Popular IDEs include Visual Studio, PyCharm,
Android Studio, etc.
1. Programming Language: The choice of IDE (Integrated Development Environment) mainly
lies with the programming language you decide on. Dedicated IDEs have automated features
that best suit the programming languages they support. While there also exist IDEs that
support multiple programming languages.
2. Operating System: Mostly all IDEs work with different Operating systems, but there exist
IDEs that might only work best on specific platforms. You may take into account the IDEs'
compatibility with various platforms and operating systems.
3. Pricing Model: Some IDEs might be freely available while some may require a premium
subscription model to unlock the majority of the features. Taking your budget and your needs,
go with the IDE that suits you the best.
4. Features: Features like version control, debugger, code highlighter, integrated terminal, and
code refactoring are some of the features that can be considered white choosing an IDE.

Advantages of using IDE


Some of common advantages of IDEs or Integrated Development Environments are as follows:
 Project Management: IDEs make viewing the project directory structure much simpler
which breaks down the tedious tasks of working with multiple files. Typically IDEs also
14 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

include a number of tools, such as syntax highlighting, code completion, and code folding,
which makes it easier to manage the overall project.
 Saving plenty of time and Effort: IDEs often include a variety of tools that can not only
assist you in organizing your code but also quickly highlight the error in your code. They
also include a flexible combination of tools for compiling, building, testing, and deploying
your code, through which you can automate these tasks eliminating the need to manually
run each task.
 Productivity: IDEs can increase your productivity by providing a centralized location for all
of your development needs, from writing and editing code to debugging and deploying.
Some of the functionality provided by IDEs can also be accomplished with a text editor and
command-line tools, but IDEs usually make the process more convenient and user-friendly.

Disadvantages of using IDE


Some of common disadvantages of IDEs or Integrated Development Environments are as
follows:
 Not beginner Friendly: IDEs are complex tools and generally provide quite an intimidating
UI, which can be a little tough to comprehend for a beginner. Maximizing their benefit
generally needs a dedicated effort.
 Frequent Updates: It's difficult to keep up with constant updates, such as new samples,
templates, and features.
 Only Assist in writing code: As a tool, IDEs (Integrated Development Environments) are
limited to being an assistant. They can't write code or automatically fix errors, one still
needs the knowledge to write clean code.
 Cost: Some IDE is Expensive or needs additional costs to unlock some add-ons, which can
be a barrier for small-scale companies or learning Individuals.

Basics of Arduino Programming:

Electronic Signals:
Let us study the two types of signals that are used for communication:
Analog Signal: Analog signals can take any value in a given continuous range of values. Generally,
analog signals used in Arduino are around 0V to 5V. The analog pins can take data up to 8-bit
resolution therefore, they are used for taking large values as input in the Arduino. These signals
carry data in a very accurate form without many errors.

Digital Signal: Digital signals can only take discrete values which are, high('1') and low('0'). These
signals are usually used to Arduino on or off which requires only two values. The collection of two
values (0 and 1) can be used to generate a sequence known as the binary sequence which is a
collection of zeroes and ones. This is how data is transmitted without much memory requirement
but this can lead to certain errors like quantization errors.

Brackets:
There are two types of brackets utilized in Arduino coding, as given below:
 Parentheses: When writing a function in IDE, the parentheses brackets are used to include
the argument parameters, such as methods, functions, or code statements. In addition to
15 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

this, the bracket is also used for defining the precedence order while dealing with
mathematical equations. These brackets are represented by '( )'.
 Curly Brackets: Curly brackets are used to open and close all the statements in the functions
or out of the functions. Note that a closed curly bracket always follows the open curly bracket
in the code for proper layout. These brackets are denoted by '{ }'.
o Open curly bracket- ' { '
o Closed curly bracket - ' } '

Line Comment:
There are two types of line comments, let us study them individually:
 Single-line comment: As the name suggests, the single lines that follow two forward slashes
are known as single-line comments. These statements are known as comments because the
compiler ignores all the characters that come after two forward slashes in a single line.
Comments are hidden when the output is presented. Comments are added for the sole
purpose of comprehension of the code and for writing necessary information for user
reference.
// This is a comment
 Multi-line comment: The single line comment extends to one line and the Multi-line
comment is used for adding comments in multiple lines. The syntax is a forward slash
followed by an asterisk symbol (/*), ending with a */. It is mostly used for commenting larger
text blocks that are not interpreted by the compiler and solely for reference purposes of
users.
/ * This is a multiline comment*/

Coding Screen:
If you open the coding screen of your IDE, you will realize that it is divided into two sections
namely, setup() and loop(). The setup segment is the first block and is implemented first for
preparing the necessary environment needed for running other commands. This coding screen is
shown below:

16 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

It is important to note that the setup and loop blocks must have statements that are enclosed
within curly brackets. Depending on the type of project you are working on, you can initialize the
setup in setup() and define other necessary statements in the loop() block. Let us study each
section individually
For example
void setup ( ) {
Coding statement 1;
Coding statement 2;
Coding statement n;
}
void loop ( ) {
Coding statement 1;
Coding statement 2;
Coding statement n;
}

Setup
Setup contains the very beginning section of the code that must be executed first. The pin modes,
libraries, variables, etc., are included in the setup section so that no problem occurs when the
remaining code runs. It is executed only once during the uploading of the program and after
resetting or powering up the Arduino board.
Zero setup () resides at the top of each sketch. When the program runs after completion, it heads
towards the setup section to initialize the setup and include all the necessary libraries all at once.

Loop
The loop contains statements that are executed repeatedly. Unlike, the setup section there is no
restriction on running this code once, it can run multiple times according to the value of variables.
Time
The basic unit of measuring time in Arduino programming is a millisecond.
1 sec = 1000 milliseconds
Timing adjustments can be made in milliseconds. A better explanation for this can be that a 2-
second delay corresponds to 2000 milliseconds.

Example
A simple example of blinking the LED using Arduino is considered.
The steps are:
1. Go to the menu bar. Click on the File button in the bar.
2. Click on the Examples in the menu bar.
3. Click on the Basics option.
4. You will see Blink, click it.
This is the window that opens:

17 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

Note: The pinMode() will be the main function in the void setup() and digitalWrite( ) and delay ( )
will be the main function in the void setup()
PinMode ( )
The pinMode() function assigns a specific PIN as either INPUT or OUTPUT.

The Syntax is:


pinMode (pin, mode)
Pin: It is used to specify the PIN which depends on the project requirements.
Mode: Depending on whether the pin is taking INPUT or OUTPUT, it specifies the pin's function.
Let's consider a situation to understand the pinMode. We want to take input from the PIN 13 and
then,
Code:
pinMode (13, INPUT);
PinMode in OUTPUT mode
Setting pinMode to OUTPUT is important for some pins. This mode allows the specified PIN to
supply sufficient current to another circuit to activate the sensor or light the LED. When set to
OUTPUT, this pin goes into a very low impedance state, making the current useful. It is important
18 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

to note that excessive current or short circuits between pins can damage the Atmel chip. This
explains the need for setting the mode to OUTPUT.

PinMode in INPUT mode


When digitalWrite() is used, selecting the INPUT mode for any pin turns off the low state and sets
the high state as the ultimate state. The INPUT mode can be employed alongside an external
pull-down resistor. For this purpose, pinMode should be set to INPUT_PULLUP. This
configuration reverses the behavior of the INPUT mode. In INPUT_PULLUP mode, a sufficient
current is provided to light an LED connected to the pin dimly. If the LED emits a dim light, it
signifies that this condition is operational.
Given these considerations, it's advisable to set the pin to OUTPUT mode to ensure proper
functionality.

digitalWrite( )
The digitalWrite( ) function is used to decide the value of the pin. It can be set as either of the two
values, HIGH or LOW.
HIGH: For a board that is supplied with a maximum of 1V, it results in a 5V value whereas on a
board with other values like 6V, it updates the value to 6V.
LOW: It sets the pin to the ground by setting a reference of 0V.
If no pin is set with pinMode as OUTPUT, the LED may light dim.
The syntax is:
digitalWrite( pin, value HIGH/LOW)
Pin: We can specify the PIN or the declared variable.
Let's understand with an example.
Example:
digitalWrite (6, HIGH);
digitalWrite (6, LOW);
The HIGH will be used for setting the pin at number 6 high and it will ultimately turn on the LED if
connected to this pin while, the LOW will be used for setting the pin at number 6 low and it will
ultimately turn off the LED if connected to this pin.

delay ( )
The delay() function serves as a tool to halt program execution for a specified duration, measured
in milliseconds. We have seen how delay(5000) signifies a stop of 5 seconds.
This can be understood by the fact that 1 second equals 1000 milliseconds.
Code:
digitalWrite (12, HIGH);
delay (5000);
digitalWrite (12, LOW);
delay (2000);
The program here is that the LED is connected to the pin having PIN 12 and it will remain lit for 5
seconds before turning and then will go off. The LED will then be turned off for 2 seconds as
specified by delay(). This cycle will continue in a loop depending on the defined variables within
the void loop() function.

19 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

Solved Example
Let us try to code the control of the LED on PIN 12, by designing it to remain ON for 3 seconds
and remain OFF for 2.5 seconds. Here is the code
Pseudocode:
Firstly, we will need to set a particular pin as the output pin therefore, we will set the pin number
12 as the input in setup() block.
Then we need to set the pin number 12 high using the digitalWrite() function.
Then we use the delay() function to keep the LED on for 3 seconds.
Then we need to set the pin number 12 low using the digitalWrite() function.
Then we use the delay() function to keep the LED off for 2.5 seconds.

void setup () {
pinMode ( 12, OUTPUT); // to set the OUTPUT mode of pin number 13.
}
void loop () {
digitalWrite (12, HIGH);
delay (3000); // 3 seconds = 3 x 1000 milliseconds
digitalWrite (12, LOW);
delay (2500); // 2.5 seconds = 2.5 x 1000 milliseconds
}

Advantages and Disadvantages of Arduino


Advantages of Arduino
We need to know the reason for selecting Arduino over other devices so let us study some
advantages of Arduino.
 Arduino is the best choice for starting your programming journey in electronics. Its easy-to-
use interface allows users to build simple projects on their own.
 There is no need for experience or hands-on experience in electronics before starting work
on Arduino. Anyone with a genuine interest in Arduino can begin learning through simple
tutorials and some guidance. These tutorials are available free of cost for creating some
beginner-level and advanced projects.
 Arduinos offer a wide range of options. You can use Arduino alone to create some projects or
you can add some extra features by integrating it with other devices like Raspberry Pie.
 Arduino is an open-source tool that can be accessed from different locations and platforms.
Due to the inexpensive nature of Arduinos, they can be used on different microcontrollers
like Atmel's ATMEGA 16U2 microcontrollers.
 Depending on the need of your project, you can avail of any Arduino that satisfies the needs.
These Arduino are available in different designs that offer different size ranges, power, and
specifications.

Disadvantages of Arduino
Let us see some limitations associated with Arduino:
 Despite being able to communicate with other boards like Raspberry pies and other
Arduinos, the communication of Arduino is very restricted since it is installed to use certain
basic communication protocols.
20 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

 Arduinos have been designed for beginner-level projects as a result they have Limited
Memory and Processing Power which limits the projects that can be made using Arduino.
 Due to the lack of excess security in Arduino boards, they can be easily hacked which can
result in loss and data leakage.
 When it comes to accuracy, the Arduino board is not the best choice since it lacks the
precision needed for analog to digital conversion.
 Arduino responds and coordinates tasks based on the responsiveness of other components
due to which it can not be programmed for real-time applications.

Application of Arduino:
Arduino finds its applications in various fields due to their ability to perform different things. Let
us see some of its applications:
 Arduinos are used in 3D printing where they perform the task of selecting how the printing
will be performed.
 Arduinos are used for creating basic designs by makers, designers, hackers, and creators
across the globe to create some great projects. Some of the projects are Laser Turret Midi
Controller, Retro Gaming With an OLED Display, and Traffic Light Controller.
 Arduinos are used in the field of robotics for programming robots and adding basic features
like sensing and responding to environmental conditions.
 Arduino is used in IoT(Internet of Things) since it can collect information using sensors. The
collected data is then processed and transmitted for developing various smart devices.

Arduino Programming:

Every Arduino program has two main functions:

void setup()

 Runs only once when the board starts.


 Used to initialize things like pin modes, serial communication, etc.

void loop()

 Runs continuously.
 Contains the main logic of your program.

Example:

void setup() {
// runs once
pinMode(13, OUTPUT);
}

void loop() {
// runs again and again
digitalWrite(13, HIGH);
21 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}

2. Pin Modes

Before using a pin, you must define whether it’s an INPUT or OUTPUT.

pinMode(pinNumber, INPUT);
pinMode(pinNumber, OUTPUT);

Example:

pinMode(7, OUTPUT);

3. Digital Output

Used to turn something ON or OFF (LED, buzzer, relay).

digitalWrite(pin, HIGH); // ON
digitalWrite(pin, LOW); // OFF

4. Digital Input

Reads HIGH/LOW signals (button, IR sensor, limit switch).

int value = digitalRead(pin);

5. Analog Input

Reads values from 0 to 1023 (temperature sensor, potentiometer).

int sensorValue = analogRead(A0);

6. PWM (Analog Output Simulation)

Pins with ~ symbol can output PWM between 0–255.

analogWrite(pin, value);

Example:

analogWrite(9, 128); // 50% brightness

7. Delay Function

Pauses program execution.


22 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
delay(milliseconds);

Example:

delay(1000); // 1 second

8. Variables

Store values.

int count = 0; // integer


float temp = 25.6; // decimal
char letter = 'A'; // character

9. Serial Communication

Used to print messages on Serial Monitor (very helpful for debugging).

Start serial communication:


Serial.begin(9600);
Print to the serial monitor:
Serial.println("Hello Arduino");
Serial.println(sensorValue);

10. Conditional Statements (if/else)


if (value == HIGH) {
// do something
} else {
// do something else
}

11. Loops (for, while)


For loop:
for (int i = 0; i < 10; i++) {
digitalWrite(13, HIGH);
delay(200);
}
While loop:
while (digitalRead(7) == HIGH) {
// repeat while button is pressed
}

12. Functions (Custom Functions)

Create your own reusable code:

void blinkLED() {
digitalWrite(13, HIGH);
23 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
delay(500);
digitalWrite(13, LOW);
delay(500);
}

Call it inside loop:

blinkLED();

13. Libraries

Arduino uses libraries to simplify complex tasks:

 <Servo.h>
 <Wire.h>
 <LiquidCrystal.h>
 <SoftwareSerial.h>

Example:

#include <Servo.h>
Servo motor;

14. Comments

Improve readability.

// Single line comment

/*
Multi-line comment
*/

15. Uploading Code

Steps:

1. Connect Arduino with USB


2. Select Tools → Board (Arduino Uno)
3. Select Tools → Port
4. Click Upload

What is Emulation and Emulator?


The capacity of a computer program that stimulates the behavior of another program or system
inside of an electrical device is known as emulation. They allow a computer, called the host
system, to run software or use peripherals designed for another system, known as the guest
system.
24 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

How were Emulators Developed?


The process of developing emulators is based on extensive study, design, implementation,
optimization, testing, and iteration. To construct the emulator's fundamental components to
reproduce the behavior of the target system on the host system, developers first analyze the
architecture and interfaces of the target system. Writing code to manage memory, conduct
input/output activities, imitate peripherals, and interpret or translate instructions are all part of
the implementation. Performance is enhanced by optimization methods including dynamic
recompilation and caching, and accuracy, stability, and compatibility are guaranteed by rigorous
testing. Users are the focus of documentation and user interface design, and community
feedback drives incremental improvements that yield flexible tools for hardware and software
emulation that run on several platforms.

Type of Emulators:
 CPU emulators: An emulator is a software application that replicates the hardware CPU.
The simplest version of the CPU emulator is an interpreter, a program that tracks the
execution path for emulated programs.
 Game console emulators: These emulators allow users to use games designed specifically
for the consoles on various platforms, such as computers, smartphones and gaming
consoles, replicating the hardware and software environment of a console.
 Operating System Emulators: The operation system emulators enable users to use a
number of operational systems simultaneously on the same hardware, simulating the
behavior of all IT systems.
 Network Emulators: Network emulators allow users to test and verify the performance,
reliability and scalability of network applications and systems by simulating real network
conditions and environments.
 Application-Specific Emulators: Application Specific emulators are aimed at replicating the
individual software components or interfaces and providing compatibility with applications
developed for a variety of platforms as well as environments.

Different Parts of Emulations:


 Emulator Core: The emulator core is an essential component of emulation software, which
interprets instructions from the guest system and transposes them to instructions that a
host computer can understand and use. It shall be responsible for emulating the CPU,
memory management, input and output functions of the guest system as well as other
essential functions.
 ROMs and BIOS: The software and data from the guest system that the emulator needs to
run are contained in the Read Only Memory ROM images. The operating system and the
firmware required to run software on a guest computer are usually included in these ROMs.
In addition, to emulate consoles and older computers, and to provide low level hardware
initialization and control, it is often necessary to have BIOS Basic Input System Output files.
 User Interface: Controls and settings for configuring emulation parameters, loading ROMs,
and managing emulation sessions are provided in the user interface of the emulator. This
enables users to configure their emulation experience, adjust settings for performance and
compatibility as well as interaction with the simulated software.
 Graphics and Audio Rendering: The components for rendering graphics and processing
audio, which replicates the visual and sound output of the guest system, are typically

25 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
included in the Emulators. In order to enhance performance and reliability, these
components may use software based rendering or hardware acceleration techniques.
 Configuration and Settings: Emulators are frequently offering a broad range of
configurations and settings which allow users to configure emulation parameters in order
to suit their preferred hardware capabilities. Options to adjust CPU speed, graphics
rendering, input mapping, and audio output configuration may be included in these
settings.

Application of Emulators:
 Gaming: Emulators allow the user to run games developed for one gaming platform on
other platforms.
 Software Development: To detect and resolve compatibility issues early in the
development process, developers always use emulators for the simulation of special
hardware configurations, operating systems or network conditions.
 Legacy Software Support: On modern platforms, emulation allows us to run legacy
software designed for outdated hardware or operating systems. This is particularly useful
for businesses and organizations that are dependent on legacy applications to perform
essential operations but must update their equipment or move to a more recent operating
system.
 Education and Training: For the teaching of computer science concepts, software
development techniques and historical computing systems, Emulators play an important
role in educational settings.

Advantage of Emulation:
 Emulation allows software which is created for one of the platforms to be used on another,
so that it can support cross compatibility with other platforms. It is especially useful to run
legacy software on new computers.
 Emulation makes it easier for users to access software and hardware that may be rare,
expensive, or difficult to obtain physically.
 By providing a platform for developers to test their software in several environments,
Emulation makes it easier to develop and test the software. Emulators can be used for
simulating various hardware configurations, operating systems and network conditions by
developers.
 In teaching computer science concepts, software development techniques and historical
computing systems, Emulation is valuable in education settings.
Disadvantage of Emulation
 Due to the necessity of translating instructions between guest and host
systems, encryption often introduces performance issues.
 It can be difficult to achieve accurate emulation of large hardware systems, resulting in
compatibility problems and incorrect simulation behaviors.
 Accurate emulation of larger hardware systems can be hard to achieve, which may lead to
compatibility issues and incorrect simulation behavior.
 It is difficult to set up and configure emulation software, requiring technical knowledge and
experience in computer hardware and software systems.

26 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
Real-World Applications of Arduino:

Arduino is used in many real-life areas beyond simple projects. It makes technology affordable
and easy to apply in daily life. From smart homes to healthcare, it provides practical solutions
that improve convenience, safety, and efficiency.

1. Home Automation
Arduino is at the heart of many smart home systems. With sensors and relays, you can control:

o Lights and fans


o Air conditioning and thermostats
o Door locks and security cameras
o Energy monitoring systems

Example: An Arduino-based motion sensor can automatically turn on lights when someone
enters a room, saving electricity and adding convenience. Many of these solutions are included
in Arduino based projects list.

2. Health Monitoring
Healthcare is one of the fastest-growing areas of applications of Arduino Uno. Arduino-
powered devices are used to track and measure vital health data.

o Heart rate monitors


o Pulse oximeters (oxygen levels)
o Fitness trackers
o Portable ECG devices

These devices provide affordable health monitoring solutions both in hospitals and at home.

3. Agriculture and Smart Farming


Farmers are increasingly using Arduino Uno applications for precision agriculture.

o Automated irrigation systems


o Soil moisture monitoring
o Weather stations for temperature and rainfall
o Crop health monitoring

Example: A soil moisture sensor connected to Arduino can turn on a water pump only when
the soil is dry, saving water and improving crop yield.

27 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
4. Education and Learning
Arduino is a favorite in schools, colleges, and STEM programs.

o Simple kits help students learn coding, electronics, and robotics.


o Hands-on projects make learning fun and practical.
o Encourages problem-solving, creativity, and teamwork.

Example: Students often build line-following robots or automatic plant watering systems as
beginner projects. For learning, many start with Arduino applications download resources.

5. Industrial Automation
Industries use Arduino to control and monitor machines.

o Process control systems


o Temperature and pressure monitoring
o Conveyor belt automation
o Quality testing devices

For small and medium industries, Arduino provides a low-cost alternative to expensive
industrial controllers. Some industries even integrate ESP32 Arduino boards for more
advanced solutions.

6. Environmental Monitoring
Arduino is widely used in environmental science and conservation projects.

o Air quality monitoring


o Water quality testing
o Weather data collection
o Wildlife tracking devices

Example: Arduino-based air monitoring systems can measure pollution levels and share real-
time data online for awareness and research.
Case Studies: Arduino in Action
Case studies show how Arduino is solving real problems in different fields. These examples
prove its value in practical use. They also highlight how simple ideas can grow into impactful
solutions that benefit society.

o Home Automation: An Arduino-based smart switch lets homeowners control lights and
appliances through a smartphone app.
o Health Tech: Affordable Arduino-based ECG machines are used in rural clinics to provide basic
healthcare diagnostics.

28 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
o Smart Farming: Indian farmers use Arduino irrigation systems that save water while improving
harvests.
o Education: Universities across the world use Arduino kits for robotics competitions.
o Industry: Small factories deploy Arduino-controlled conveyor belts for cost-effective
automation.
o Environment: Wildlife researchers track endangered species with Arduino-powered GPS
collars.

Benefits of Using Arduino:

The biggest benefit of Arduino is its low cost and ease of use, making it perfect for beginners
and experts. Its large global community also helps users share ideas, tutorials, and ready-made
codes.

o Low Cost: Cheaper than traditional microcontrollers and PLCs.


o Quick Prototyping: Ideal for testing ideas before large-scale implementation.
o Large Community: Thousands of free tutorials, open-source projects, and libraries.
o Flexibility: Works with IoT modules (Wi-Fi, Bluetooth, LoRa) and AI integration.

Challenges with Arduino:

Arduino has limits in processing power, so it cannot handle very heavy tasks. Managing many
boards together and ensuring data security are also key challenges.

o Limited Processing Power: Not ideal for very complex or AI-heavy tasks.
o Scalability Issues: Managing many Arduino boards in large projects can be tricky.
o Security Concerns: Being open-source, users must take care when handling sensitive data.

Solution: These challenges can be overcome by combining Arduino with stronger processors
(like Raspberry Pi), using proper encryption, and writing optimized code.

Future Potential of Arduino:

Arduino will grow stronger with IoT, AI, and renewable energy projects. It will play a big role in
smart cities, healthcare, and automation in the future.

o IoT (Internet of Things): Smart cities, connected vehicles, and smart grids.
o Artificial Intelligence: AI-enabled Arduino projects with edge computing.
o Renewable Energy: Solar and wind power monitoring systems.
o Healthcare Innovation: Affordable diagnostic tools for rural healthcare.

29 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

Role of Arduino in IoT:


In IoT, the Arduino acts as the brain of a device, collecting data from sensors, processing it, and
connecting to the internet to send data or receive commands. Its role is to serve as a low-cost,
open-source platform for rapid prototyping and development, making it ideal for creating
everything from smart home devices to environmental monitoring systems.
Key roles of Arduino in IoT
 Sensor data collection: Arduino boards have input/output (I/O) pins to connect with various
sensors, such as temperature, humidity, and motion sensors. It reads data from these sensors to
understand the device's environment.

 Data processing: The microcontroller on the Arduino board processes the raw sensor data,
performing calculations and logic based on its programming. This allows it to make decisions on
what to do with the information it gathers.

 Connectivity: Arduino needs a connectivity module, like a Wi-Fi or Bluetooth module


(e.g., ESP8266), to connect to the internet. This enables it to transmit the processed data to a
cloud service or receive commands from a user's application or the cloud.

 Actuator control: Once it receives data or a command, the Arduino can control actuators to
perform actions. For example, it can turn a light on or off, adjust a motor, or trigger an alert.

 Prototyping and development: Due to its simplicity, affordability, and large community support,
Arduino is an excellent tool for building and testing new IoT concepts quickly. Makers can easily
modify its code to create a wide range of projects and applications.

Examples of Arduino in IoT


 Smart Home: Creating systems to control lights, appliances, and security from a smartphone.

 Environmental Monitoring: Building weather stations that report data to the internet or
automated systems that monitor soil moisture in agriculture.

 Healthcare: Developing wearable devices that track health metrics like heart rate and
temperature.

 Industrial applications: Monitoring machinery for predictive maintenance in an industrial


setting.

Using Libraries:
Arduino programming extensively uses libraries to extend functionality and simplify interactions
with hardware components. Here's how to use them:
1. Installing Libraries:
 Using the Library Manager (Recommended):
30 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
 Open the Arduino IDE.

 Navigate to Sketch > Include Library > Manage Libraries... (or click the Library Manager icon in
IDE 2.x).

 Search for the desired library by name or topic.

 Select the library and click "Install." You can also choose a specific version if needed.
 Installing a .ZIP Library:
 Download the library as a .ZIP file (e.g., from GitHub).

 In the Arduino IDE, go to Sketch > Include Library > Add .ZIP Library....

 Select the downloaded .ZIP file and click "Open."

2. Including Libraries in Your Sketch:


 Once installed, you need to include the library in your Arduino sketch to use its functions and
classes.

 Automatic Inclusion: Go to Sketch > Include Library and select the desired library from the
list. The IDE will automatically add the necessary #include statement at the beginning of your
code.

 Manual Inclusion: You can manually add the #include statement at the top of your sketch:
C++
#include <LibraryName.h>
Replace LibraryName.h with the actual header file of the library.

3. Using Library Functions and Classes:


 Creating an Instance (if applicable): Many libraries use object-oriented programming, requiring
you to create an instance of a class before using its functions. For example, with the Servo
library:
C++
#include <Servo.h>

Servo myServo; // Creates an instance of the Servo class


 Calling Functions: Access functions provided by the library or the created instance using the dot
operator (.). For example:
C++
myServo.attach(9); // Attaches the servo to digital pin 9
myServo.write(90); // Moves the servo to 90 degrees
 Referring to Library Documentation/Examples: Libraries often come with examples and
documentation (sometimes found on their GitHub repositories or in the Arduino IDE's File >
Examples > Examples from Custom Libraries section). These resources are crucial for
understanding how to use specific functions and classes within a library.
31 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

Addition in Arduino:
In Arduino, "additions" can refer to both the mathematical addition operator ( + ) for calculations
and the physical addition of components like sensors or actuators to a board. To add numbers,
use the + operator in a sketch, such as c = a + b; . To add components, connect them to the
board's input/output pins, power pins (like VIN , 5V , or GND ), or use the serial communication
pins.
Mathematical addition in Arduino code
 Operator: The plus sign ( + ) is used for addition.

 Syntax: sum = operand1 + operand2; .

 Example:

cpp

int a = 5;
int b = 10;
int c;
c = a + b; // c will now hold the value 15 [3]
 Important notes:

o If you add an int and a float , floating-point math will be used, but if the result is stored in
an int variable, the decimal part will be lost.

o Be mindful of integer overflow, which happens when the result of a calculation is too large to fit
in the variable's data type.

Arithmetic Operations in Arduino:

Introduction

Arduino IDE is capable of doing basic arithmetic operations. Arduino has the following five
arithmetic operators for basic mathematical operations:

Operators Operator Symbol Example

Addition + a = b + 2017

Subtraction - b = 2017 - a

32 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
Operators Operator Symbol Example

Multiplication * d = 2.5 * e

Division / e = d / 2.5

Remainder % f = d % 2.5

Addition:
The addition operator is used for adding two numbers. Here is an example:
int Num1 = 15;
int Num2 = 3;
int Sum;

void setup(){
Serial.begin(9600);
Sum = Num1 + Num2;
Serial.print("Addition of Num1 and Num2 is ");
Serial.println(Sum);
}

void loop() {
}

Serial Monitor Response: Addition of Num1 and Num2 is 18

Explanation: In the code above, two variables are defined, namely Num1 and Num2. A value is
assigned to both of them as well. The third variable, i.e. Sum is defined and no value is assigned to
it; hence, it contains a random number. This variable is used to store the sum of Num1 and Num2;
this value will overwrite the random value when you assign it to Sum. After statement 5 is
executed, the Sum will have a value of 18.

Subtraction:
The subtraction operator subtracts one number from another. It is represented by the plus sign
(+). Given below is an example:
int Num1 = 15;
int Num2 = 3;
int Result;
void setup(){
Serial.begin(9600);
Result = Num1 - Num2;
Serial.print("Subtraction of Num1 and Num2 is ");
Serial.println(Result);
}
33 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070

void loop() {
}

Serial Monitor Response: Subtraction of Num1 and Num2 is 12

The result of this operation is 12.

Multiplication:
The multiplication operator multiplies one number with another. It is represented by the asterisk
(*). Given below is an example:
int Num1 = 15;
int Num2 = 3;
int Result;
void setup(){
Serial.begin(9600);
Result = Num1 * Num2;
Serial.print("Multiplication of Num1 and Num2 is ");
Serial.println(Result);
}

void loop() {
}
Serial Monitor Response: Multiplication of Num1 and Num2 is 15

The result of this operation is 45.

Division:
The division operator divides one number by another. It is represented by the division sign (/).
Given below is an example:

int Num1 = 15;


int Num2 = 3;
int Result;

void setup(){
Serial.begin(9600);
Result = Num1 / Num2;
Serial.print("Division of Num1 and Num2 is ");
Serial.println(Result);
}

void loop() {
}

Serial Monitor Response: Division of Num1 and Num2 is 5

The result of this operation is 5.


34 Siddhartha Maurya
+91-8090797792
VISION INSTITUTE OF TECHNOLOGY, Internet Of Things
ALIGARH SUBJECT CODE: BCS 070
There is, however, one more thing you should know about division. Till now we have used division
only for integers and have got an integer as a result. But what if the result is a floating-point
number (numbers with a decimal) and not an integer? Let’s find out with the help of the example
given below:

int Num1 = 6;
int Num2 = 5;
int Result;

void setup(){
Serial.begin(9600);
Result = Num1 / Num2;
Serial.print("Division of Num1 and Num2 is ");
Serial.println(Result);
}

void loop() {
}
Serial Monitor Response: Division of Num1 and Num2 is 1

The result will be 1 because the numbers after the decimal point are discarded when the result is
stored in the variable because its data type is int. However, if we use float as the data type of the
variable to store the result, we get the correct result.

int Num1 = 6;
int Num2 = 5;
float Result;

void setup(){
Serial.begin(9600);
Result = (float) Num1 / Num2;
Serial.print("Division of Num1 and Num2 is ");
Serial.println(Result);
}

void loop() {
}
Serial Monitor Response: Division of Num1 and Num2 is 1.20

35 Siddhartha Maurya
+91-8090797792

You might also like