SlideShare a Scribd company logo
1
WINTER TRAINING PROJECT
ON
"ARDUINO WITH C PROGRAMMING"
Guru Tegh Bahadur Institute Of Technology
G-8 Area, Rajouri Garden, New Delhi 110064
Submitted By:
Govind Jha
2
Acknowledgement
I have taken efforts in this winter training. However, it would not have been possible
without the kind support and help of many individuals and organizations. I would like
to extend my sincere thanks to all of them.
I am highly indebted to PhD. Ian G. Harris for his guidance and constant supervision
as well as for providing necessary information regarding the training & also for his
support in completing the project.
I would like to express my gratitude towards my parents & members of university of
California, Irvine for their kind co-operation and encouragement which helped me in
completion of this training.
I would like to express my special gratitude and thanks to coursera for giving me an
opportunity to access the course material.
My thanks and appreciations also go to my colleague in developing the report and
people who have willingly helped me out with their abilities.
3
Contents
1. Introduction to Arduino ………………………………………………4
2. Advantages of Arduino platform……………………………………...5
3. Arduino Hardware…………………………………………………….6
4. Arduino Board Schematic Representation……………………………7
 Components
 Digital Pins
 Analog Pins
 Power Pins
 Other Pins
5. Arduino Shields……………………………………………………….11
 Prototyping
 Ethernet, Wi-Fi, Wireless, GPS, Etc.
 Music and Sound
 Displays and Cameras
 Motor Drivers
6. Arduino UNO…………………………………………………………17
 Pin Description
 Arduino UNO Schematics
7. Arduino Software Development………………………………………20
 Arduino IDE
 Writing Sketches
 Arduino libraries
 Standard Libraries
8. C Programming Language in Arduino………………………………..23
4
9. Explaining your Code……………………………………………..24
 Using Variables
10. C Operators………………………………………………………26
11. Conditional Statements in C……………………………………..27
 If
 If else
 If else if
12. Loops…………………………………………………………….29
 For loop
 Do loop
 Do while loop
13. Break and Continue……………………………………………...31
14. Functions………………………………………………………...32
 Defining a Function
 Defining a Function
 Calling a Function
 Function Arguments
15. Switch case in C…………………………………………………36
16. Blink Example In Arduino ……………………………………...37
5
Introduction to Arduino Platform
Arduino is an open-source computer hardware and software platform for building digital devices and
interactive objects that can sense and control the digital world around them. For example, Arduino
boards are able to read inputs - light on a sensor, a finger on a button, or a Twitter message - and turn
it into an output - activating a motor, turning on an LED, publishing something online. You can tell
your board what to do by sending a set of instructions to the microcontroller on the board. To do so
you use the Arduino programming language (based on Wiring), and the Arduino Software (IDE),
based on Processing. Thus, Arduino platform works in terms of the physical board and the libraries
and the IDE (integrated development environment).
Arduino board designs use a variety of microprocessors and controllers. The boards are equipped
with sets of digital and analog input/output (I/O) pins that may be interfaced to various expansion
boards (shields) and other circuits. The boards feature serial communications interfaces,
including Universal Serial Bus (USB) on some models, which are also used for loading programs
from personal computers. The microcontrollers are typically programmed using a dialect of features
from the programming languages C and C++. In addition to using traditional compiler tool chains,
the Arduino project provides an integrated development environment (IDE) based on
the Processing language project.
Over the years Arduino has been the brain of thousands of projects, from everyday objects to
complex scientific instruments. A worldwide community of makers - students, hobbyists, artists,
programmers, and professionals - has gathered around this open-source platform, their contributions
have added up to an incredible amount of accessible knowledge that can be of great help to novices
and experts alike.
6
Advantages of Arduino
Arduino is an open source, computer hardware and software company, project, and user community
that designs and manufactures microcontroller kits for building digital devices and interactive objects
that can sense and control objects in the physical world. The project's products are distributed
as open-source hardware and software, which are licensed under the GNU Lesser General Public
License (LGPL) or the GNU General Public License (GPL),[1] permitting the manufacture of
Arduino boards and software distribution by anyone. Arduino boards are available commercially in
preassembled form, or as do-it-yourself kits.
Arduino was born at the Ivrea Interaction Design Institute as an easy tool for fast prototyping, aimed
at students without a background in electronics and programming. As soon as it reached a wider
community, the Arduino board started changing to adapt to new needs and challenges, differentiating
its offer from simple 8-bit boards to products for IoT applications, wearable, 3D printing, and
embedded environments. All Arduino boards are completely open-source, empowering users to build
them independently and eventually adapt them to their particular needs. The software, too, is open-
source, and it is growing through the contributions of users worldwide.
Thanks to its simple and accessible user experience, Arduino has been used in innumerable different
projects and applications. The Arduino software is easy-to-use for beginners, yet flexible enough for
advanced users. It runs on Mac, Windows, and Linux. Teachers and students use it to build low cost
scientific instruments, to prove chemistry and physics principles, or to get started with programming
and robotics. Designers and architects build interactive prototypes, musicians and artists use it for
installations and to experiment with new musical instruments. Makers, of course, use it to build
many of the projects exhibited at the Maker Faire, for example. Arduino is a key tool to learn new
things. Anyone - children, hobbyists, artists, programmers - can start tinkering just following the step
by step instructions of a kit, or sharing ideas online with other members of the Arduino community.
 Inexpensive - Arduino boards are relatively inexpensive compared to other microcontroller
platforms. The least expensive version of the Arduino module can be assembled by hand, and even
the pre-assembled Arduino modules cost less than $50
 Cross-platform - The Arduino Software (IDE) runs on Windows, Macintosh OSX, and Linux
operating systems. Most microcontroller systems are limited to Windows.
 Simple, clear programming environment - The Arduino Software (IDE) is easy-to-use for
beginners, yet flexible enough for advanced users to take advantage of as well. For teachers, it's
conveniently based on the Processing programming environment, so students learning to program in
that environment will be familiar with how the Arduino IDE works.
 Open source and extensible software - The Arduino software is published as open source
tools, available for extension by experienced programmers. The language can be expanded through
C++ libraries, and people wanting to understand the technical details can make the leap from
Arduino to the AVR C programming language on which it's based. Similarly, you can add AVR-C
code directly into your Arduino programs if you want to.
 Open source and extensible hardware - The plans of the Arduino boards are published
under a Creative Commons license, so experienced circuit designers can make their own version of
the module, extending it and improving it. Even relatively inexperienced users can build
the breadboard version of the module in order to understand how it works and save money.
7
Arduino Hardware
Arduino is open-source hardware. Most Arduino boards consist of an Atmel 8-bit
AVR microcontroller (ATmega8, ATmega168, ATmega328, ATmega1280, ATmega2560) with
varying amounts of flash memory, pins, and features. The 32-bit Arduino Due, based on the Atmel
SAM3X8E was introduced in 2012. The boards use single or double-row pins or female headers that
facilitate connections for programming and incorporation into other circuits. These may connect with
add-on modules termed shields. Multiple, and possibly stacked shields may be individually
addressable via an I²C serial bus. Most boards include a 5 V linear regulator and a 16 MHz crystal
oscillator or ceramic resonator. Some designs, such as the Lily Pad, run at 8 MHz and dispense with
the on board voltage regulator due to specific form-factor restrictions.
Arduino microcontrollers are pre-programmed with a boot loader that simplifies uploading of
programs to the on-chip flash memory. The default boot loader of the Aduino UNO is the opt boot
loader. Boards are loaded with program code via a serial connection to another computer. Some
serial Arduino boards contain a level shifter circuit to convert between RS-232 logic levels
and transistor–transistor logic (TTL) level signals. Current Arduino boards are programmed
via Universal Serial Bus (USB), implemented using USB-to-serial adapter chips such as
the FTDI FT232. Some boards, such as later-model Uno boards, substitute the FTDI chip with a
separate AVR chip containing USB-to-serial firmware, which is reprogrammable via its own ICSP
header. Other variants, such as the Arduino Mini and the unofficial Boarduino, use a detachable
USB-to-serial adapter board or cable, Bluetooth or other methods, when used with traditional
microcontroller tools instead of the Arduino IDE, standard AVR in-system programming (ISP)
programming is used.
The Arduino board exposes most of the microcontroller's I/O pins for use by other circuits.
The Diecimila, Duemilanove, and current Uno provide 14 digital I/O pins, six of which can
produce pulse-width modulated signals, and six analog inputs, which can also be used as six digital
I/O pins. These pins are on the top of the board, via female 0.1-inch (2.54 mm) headers. Several
plug-in application shields are also commercially available. The Arduino Nano, and Arduino-
compatible Bare Bones Board and Boarduino boards may provide male header pins on the underside of
the board that can plug into solderless breadboards.
Many Arduino-compatible and Arduino-derived boards exist. Some are functionally equivalent to an
Arduino and can be used interchangeably. Many enhance the basic Arduino by adding output drivers,
often for use in school-level education, to simplify making buggies and small robots. Others are
electrically equivalent but change the form factor, sometimes retaining compatibility with shields,
sometimes not. Some variants use different processors, of varying compatibility.
8
Arduino Boards
The original Arduino hardware was produced by the Italian company Smart Projects. Some Arduino-
branded boards have been designed by the American companies SparkFun Electronics and Adafruit
Industries. As of 2016, 17 versions of the Arduino hardware have been commercially produced.
Some of the Arduino boards are:
 Arduino RS232
 Arduino Diecimila
 Arduino Duemilanove
 Arduino Uno R2
 Arduino Uno SMD R3
 Arduino Leonardo
 Arduino Pro
 Arduino LilyPad 00
 Arduino Mega
 Arduino Nano
 Arduino Robot
 Arduino Esplora
 Arduino Ethernet
 Arduino Yun
 Arduino Due
Arduino Uno R2 Arduino LilyPad 00
9
Arduino Nano Arduino Yun
Arduino Diecimila Arduino Uno R2
Arduino Mega Arduino Leonardo
10
Arduino Board Schematic Representation
Components:-
 Analog Reference pin (orange)
 Digital Ground (light green)
 Digital Pins 2-13 (green)
 Digital Pins 0-1/Serial In/Out - TX/RX (dark green) - These pins cannot be used for digital i/o
(digitalRead and digitalWrite) if you are also using serial communication (e.g. Serial.begin).
 Reset Button - S1 (dark blue)
 In-circuit Serial Programmer (blue-green)
 Analog In Pins 0-5 (light blue)
 Power and Ground Pins (power: orange, grounds: light orange)
 External Power Supply In (9-12VDC) - X1 (pink)
 Toggles External Power and USB Power (place jumper on two pins closest to desired supply) -
SV1 (purple)
 USB (used for uploading sketches to the board and for serial communication between the board and
the computer; can be used to power the board) (yellow)
Digital Pins
In addition to the specific functions listed below, the digital pins on an Arduino board can be used
for general purpose input and output via the pinMode(), digitalRead(), and digitalWrite() commands.
Each pin has an internal pull-up resistor which can be turned on and off using digitalWrite() (w/ a
value of HIGH or LOW, respectively) when the pin is configured as an input. The maximum current
per pin is 40 mA.
11
 Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. On the Arduino
Diecimila, these pins are connected to the corresponding pins of the FTDI USB-to-TTL Serial chip.
On the Arduino BT, they are connected to the corresponding pins of the WT11 Bluetooth module.
On the Arduino Mini and LilyPad Arduino, they are intended for use with an external TTL serial
module (e.g. the Mini-USB Adapter).
 External Interrupts: 2 and 3. These pins can be configured to trigger an interrupt on a low value, a
rising or falling edge, or a change in value. See the attachInterrupt() function for details.
 PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output with the analogWrite() function. On boards
with an ATmega8, PWM output is available only on pins 9, 10, and 11.
 BT Reset: 7. (Arduino BT-only) Connected to the reset line of the bluetooth module.
 SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication, which,
although provided by the underlying hardware, is not currently included in the Arduino language.
 LED: 13. On the Diecimila and LilyPad, there is a built-in LED connected to digital pin 13. When
the pin is HIGH value, the LED is on, when the pin is LOW, it's off.
Analog Pins
In addition to the specific functions listed below, the analog input pins support 10-bit analog-to-
digital conversion (ADC) using the analogRead() function. Most of the analog inputs can also be
used as digital pins: analog input 0 as digital pin 14 through analog input 5 as digital pin 19. Analog
inputs 6 and 7 (present on the Mini and BT) cannot be used as digital pins.
 I2C: 4 (SDA) and 5 (SCL). Support I2C (TWI) communication using the Wire library (documentation
on the Wiring website).
Power Pins
 VIN (sometimes labelled "9V"). The input voltage to the Arduino board when it's using an external
power source (as opposed to 5 volts from the USB connection or other regulated power source). You
can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this
pin. Note that different boards accept different input voltages ranges, please see the documentation
for your board. Also note that the LilyPad has no VIN pin and accepts only a regulated input.
 5V. The regulated power supply used to power the microcontroller and other components on the
board. This can come either from VIN via an on-board regulator, or be supplied by USB or another
regulated 5V supply.
 3V3. (Diecimila-only) A 3.3 volt supply generated by the on-board FTDI chip.
 GND. Ground pins.
Other Pins
 AREF. Reference voltage for the Analog inputs. Not currently supported by the Arduino software.
 Reset. (Diecimila-only) Bring this line LOW to reset the microcontroller. Typically used to add a
reset button to shields which block the one on the board.
12
Arduino Shields
Arduino and Arduino-compatible boards use printed circuit expansion boards called shields, Shields
are boards that can be plugged on top of the Arduino PCB extending its capabilities. The different
shields follow the same philosophy as the original toolkit: they are easy to mount, and cheap to
produce.
Shields can provide motor controls for 3D printing and other applications, Global Positioning
System (GPS), Ethernet, liquid crystal display (LCD), or bread boarding (prototyping). Several
shields can also be made do it yourself (DIY)
Many Arduino shields are stackable. You can connect many shields together to create a “Big Mac”
of Arduino modules. You could, for example, combine an Arduino Uno with a Voice Box Shield,
and a WiFly Shield to create a WiFi Talking Stephen Hawking.
Shields are often supplied with either an example sketch, or a library. So, not only do they just
simply plug into your Arduino, but all you need to do to make them work is upload up some example
code to the Arduino.
Every Arduino shield must have the same form-factor as the standard Arduino. Power and ground
pins on one eight (previously six) pin header, and analog pins on a six-pin header next to that. Digital
pins cover the other edge on the other side, an eight-pin header separated from a 10-pin by that weird
0.5" spacing. Some shields also require a connection to the Arduino’s ICSP header (the 2x3
programming header on the end).
13
Some shields use every pin on the Arduino, while others only use a couple. When stacking shields,
it’s important to make sure they don’t use overlapping pins. Some shields communicate with the
Arduino via SPI, I2C, or Serial, and others use the Arduino’s interrupts or analog inputs.
Prototyping
Prototyping shields don’t add much functionality to the Arduino, but they do help in other ways.
These shields might do something as simple as breaking out the Arduino pins to screw terminals. In
general they make wiring to the Arduino easier.
 ProtoShield Kit - The self-titled star of this category. This shield is basically a big
prototyping area. You can stick a mini-breadboard on top, or just solder directly to the
shield’s prototyping area.
14
 ProtoScrew Shield - Like the ProtoShield, but each pin is also broken out to a screw
terminal. Handy for connecting to external motors or heavy-duty sensors.
 Go-Between Shield - The intention of this shield is to sit in between two shields. It swaps the
pins of the top shield, so they don’t interfere with each other.
 LiPower Shield - This shield allows you to power your Arduino with a Lithium
Polymer battery.
 Danger Shield - The most awesomest shield evar! This shield is a crazy conglomeration of
displays, potentiometers, and other sensors. Great for learning the ins and outs of Arduino or
incorporating into audio mixing projects.
 Joystick Shield Kit - This makes your Arduino a bare-bones controller. With a joystick and
four buttons, this makes for a great robot controller.
 microSD Shield - The Arduino has limited storage space, but this easy-to-use shield (along
with the SD library) allow for plenty of extra storage.
Ethernet, WiFi, Wireless, GPS, Etc.
 Arduino Ethernet Shield - This is one of the more classic shields. The Ethernet Shield
supplies your Arduino with an ability to connect to the World Wide Web. There’s a
great library to support it as well.
15
 WiFly Shield - SparkFun’s WiFi Shield mainstay, this shield equips your Arduino with the
ability to connect to 802.11b/g wireless networks. Then it can act as either a web server,
client, or both.
 Arduino Wi-Fi Shield - This is the Arduino Ethernet Shield sans wires. This shield can get
your Arduino connected to a WiFi router, so it can host webpages and scour the Internet.
 Electric Imp Shield - Electric Imp is a unique WiFi module, which looks like an SD card,
but it packs a powerful cloud-based WiFi controller. This is probably the least expensive
WiFi-enabling Arduino shield.
 XBee Shield - XBee’s won’t get you connected to the Internet, but they do provide a solid,
cheap means for communicating wirelessly. You could use an XBee to wirelessly trigger
coffee machines, sprinklers, lights, or other household appliances.
 Cellular Shield w/ SM5100B - Turn your Arduino into a cellular phone! Send SMS text
messages, or hook up a microphone and speaker and use it to replace your iPhone.
 GPS Shield - GPS isn’t as complicated as you might think. With a GPS Shield, your Arduino
will always know where it is.
Music and Sound
 MP3 Player Shield - Turn your Arduino into an MP3 player. Just plug in a µSD card, add
some speakers, upload the example code, and you can make your very own MP3 Playing
Music Box
16
 Music Instrument Shield - Use the MIDI protocol to turn your Arduino into a bank of
musical instruments. It can make drums, piano, woodwinds, brass, and all sorts of other
sound effects.
 Spectrum Shield - The Spectrum Shield listens to audio, and sorts it into bins of different
frequencies. Use it to make a nifty graphic equalizer display.
 VoiceBox Shield - Give your Arduino a mechanical, robotic voice.
Displays and Cameras
 Color LCD Shield - Equip your Arduino with a unique 128x128 cellular phone color LCD.
 EL Escudo - Electroluminescent wire is awesome! Use this shield to add up to eight strands of
EL wire to your project. You can finally make that Arduino-powered Tron costume.
17
 CMUcam - This camera module adds vision to your Arduino. You can use it to track blobs,
so your robot doesn’t hit any traffic cones.
Motor Drivers
 Ardumoto Motor Driver Shield - This classic motor driver shield can control two DC
motors.
 Monster Moto Shield - If you need to drive beefier motors than the Ardumoto Shield can
handle, this is the next step up.
 PWM Shield - Usually when you think pulse-width modulation (PWM), you might think
“dimming LEDs”, but PWM is also used to drive servo motors. This shield can be used to
drive your crazy 12-servo hexapod.
18
Arduino UNO
Arduino/Genuino Uno is a microcontroller board based on the ATmega328P (datasheet). It has 14
digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16 MHz quartz
crystal, a USB connection, a power jack, an ICSP header and a reset button. It contains everything
needed to support the microcontroller; simply connect it to a computer with a USB cable or power it
with a AC-to-DC adapter or battery to get started. The Uno differs from all preceding boards in that
it does not use the FTDI USB-to-serial driver chip. Instead, it features the Atmega8U2 programmed
as a USB-to-serial converter
"Uno" means one in Italian and was chosen to mark the release of Arduino Software (IDE) 1.0. The
Uno board and version 1.0 of Arduino Software (IDE) were the reference versions of Arduino, now
evolved to newer releases. The Uno board is the first in a series of USB Arduino boards, and the
reference model for the Arduino platform.
19
Pin Description
Input and Output
Each of the 14 digital pins on the Arduino Uno can be used as an input or output, using pinMode(),
digitalWrite(), and digitalRead() functions. They operate at 5 volts. Each pin can provide or receive a
maximum of 40 mA and has an internal pull-up resistor (disconnected by default) of 20-50 kOhms.
In addition, some pins have specialized functions:
Serial: pins 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. These pins
are connected to the corresponding pins of the ATmega8U2 USB-to-TTL Serial chip.
External Interrupts: pins 2 and 3. These pins can be configured to trigger an interrupt on a low
value, a rising or falling edge, or a change in value. See the attachInterrupt() function for details.
PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output with the analogWrite() function.
SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication using the
SPI library.
LED: 13. There is a built-in LED connected to digital pin 13. When the pin is HIGH value, the LED
is on, when the pin is LOW, it’s off.
The Uno has 6 analog inputs, labeled A0 through A5, each of which provide 10 bits of resolution
(i.e. 1024 different values). By default they measure from ground to 5 volts, though is it possible to
change the upper end of their range using the AREF pin and the analogReference() function.
Additionally, some pins have specialized functionality:
TWI: A4 or SDA pin and A5 or SCL pin. Support TWI communication using the Wire library.
There are a couple of other pins on the board:
AREF. Reference voltage for the analog inputs. Used with analogReference().
Reset. Bring this line LOW to reset the microcontroller. Typically used to add a reset button to
shields which block the one on the board.
20
Arduino UNO Schematics
Schematics are a traditional way to convey the hardware designs.its a diagram of what components
are on the device and how they are wired together. They are used for implementing and wiring the
components together which are present on the standard arduino chip.the arduino designs are open
source ,so hardware schematics are also open source.with the help of the]is you can design your own
circuit.
21
Arduino Software Development
A program for Arduino may be written in any programming language for a compiler that produces
binary machine code for the target processor. Atmel provides a development environment for their
microcontrollers, AVR Studio and the newer Atmel Studio.[39][40][41]
The Arduino project provides the Arduino integrated development environment (IDE), which is
a cross-platform application written in the programming language Java. It originated from the IDE
for the languages Processing and Wiring. It includes a code editor with features such as text cutting
and pasting, searching and replacing text, automatic indenting, brace matching, and syntax
highlighting, and provides simple one-click mechanisms to compile and upload programs to an
Arduino board. It also contains a message area, a text console, a toolbar with buttons for common
functions and a hierarchy of operation menus.
The Arduino IDE supports the languages C and C++ using special rules of code structuring. The
Arduino IDE supplies a software library from the Wiring project, which provides many common
input and output procedures. User-written code only requires two basic functions, for starting the
sketch and the main program loop, that are compiled and linked with a program stub main() into an
executable cyclic executive program with the GNU toolchain, also included with the IDE
distribution. The Arduino IDE employs the program avrdude to convert the executable code into a
text file in hexadecimal encoding that is loaded into the Arduino board by a loader program in the
board's firmware.
Arduino IDE
The Arduino Integrated Development Environment - or Arduino Software (IDE) - contains a text
editor for writing code, a message area, a text console, a toolbar with buttons for common functions
and a series of menus. It connects to the Arduino and Genuino hardware to upload programs and
communicate with them.
22
Writing Sketches
Programs written using Arduino Software (IDE) are called sketches. These sketches are written in
the text editor and are saved with the file extension .ino. The editor has features for cutting/pasting
and for searching/replacing text. The message area gives feedback while saving and exporting and
also displays errors. The console displays text output by the Arduino Software (IDE), including
complete error messages and other information. The bottom righthand corner of the window displays
the configured board and serial port. The toolbar buttons allow you to verify and upload programs,
create, open, and save sketches, and open the serial monitor.
 Verify
Checks your code for error while compiling it.
 Upload
Compiles your code and uploads it to the configured board. See uploading below for details.
 New
Creates a new sketch.
23
 Open
Presents a menu of all the sketches in your sketchbook. Clicking one will open it within the current
window overwriting its content.
 Save
Saves your sketch.
 Serial monitor
Opens the serial monitor.
Additional commands are found within the five menus: File, Edit, Sketch, Tools, Help. The menus
are context sensitive, which means only those items relevant to the work currently being carried out
are available.
Arduino libraries
Libraries provide extra functionality for use in sketches, e.g. working with hardware or manipulating
data. To use a library in a sketch, select it from the Sketch > Import Library menu. This will insert
one or more #include statements at the top of the sketch and compile the library with your sketch.
Because libraries are uploaded to the board with your sketch, they increase the amount of space it
takes up. If a sketch no longer needs a library, simply delete its #includestatements from the top of
your code.
The Arduino environment can be extended through the use of libraries, just like most programming
platforms. Libraries provide extra functionality for use in sketches, e.g. working with hardware or
manipulating data. To use a library in a sketch, select it from Sketch > Import Library.
A number of libraries come installed with the IDE, but you can also download or create your own.
Standard Libraries
 EEPROM - reading and writing to "permanent" storage
 Ethernet / Ethernet 2 - for connecting to the internet using the Arduino Ethernet Shield, Arduino
Ethernet Shield 2 and Arduino Leonardo ETH
 Firmata - for communicating with applications on the computer using a standard serial protocol.
 GSM - for connecting to a GSM/GRPS network with the GSM shield.
 Liquid Crystal - for controlling liquid crystal displays (LCDs)
 SD - for reading and writing SD cards
 Servo - for controlling servo motors
 SPI - for communicating with devices using the Serial Peripheral Interface (SPI) Bus
 Software Serial - for serial communication on any digital pins. Version 1.0 and later of Arduino
incorporate Mikal Hart's New SoftSerial library as Software Serial.
 Stepper - for controlling stepper motors
 TFT - for drawing text , images, and shapes on the Arduino TFT screen
 WiFi - for connecting to the internet using the Arduino WiFi shield
24
C Programming Language in Arduino
Every full C program begins inside a function called "main". A function is simply a collection of
commands that do "something". The main function is always called when the program first executes.
From main, we can call other functions, whether they be written by us or by others or use built-in
language features. To access the standard functions that comes with your compiler, you need to
include a header with the #include directive. What this does is effectively take everything in the
header and paste it into your program.
#include <stdio.h>
int main()
{
printf( "I am alive! Beware.n" );
getchar();
return 0;
}
The #include is a "preprocessor" directive that tells the compiler to put code from the header called
stdio.h into our program before actually creating the executable. By including header files, you can
gain access to many different functions--both the printf and getchar functions are included in stdio.h.
The next important line is int main(). This line tells the compiler that there is a function named main,
and that the function returns an integer, hence int. The "curly braces" ({ and }) signal the beginning
and end of functions and other code blocks.
The printf function is the standard C way of displaying output on the screen. The quotes tell the
compiler that you want to output the literal string as-is (almost). The 'n' sequence is actually treated
as a single character that stands for a newline (we'll talk about this later in more detail); for the time
being, just remember that there are a few sequences that, when they appear in a string literal, are
actually not displayed literally by printf and that 'n' is one of them. The actual effect of 'n' is to
move the cursor on your screen to the next line. Notice the semicolon: it tells the compiler that you're
at the end of a command, such as a function call. You will see that the semicolon is used to end many
lines in C.
The next command is getchar(). This is another function call: it reads in a single character and waits
for the user to hit enter before reading the character. This line is included because many compiler
environments will open a new console window, run the program, and then close the window before
you can see the output. This command keeps that window from closing because the program is not
done yet because it waits for you to hit enter. Including that line gives you time to see the program
run.
Finally, at the end of the program, we return a value from main to the operating system by using the
return statement. This return value is important as it can be used to tell the operating system whether
our program succeeded or not. A return value of 0 means success.
The final brace closes off the function. if you save the code into a file, save it as a .c file, and then
compile it. If you are using a command-line compiler, such as Borland C++ 5.5, you should read the
compiler instructions for information on how to compile.
25
Explaining your Code
Comments are critical for all but the most trivial programs and this tutorial will often use them to
explain sections of code. When you tell the compiler a section of text is a comment, it will ignore it
when running the code, allowing you to use any text you want to describe the real code. To create a
comment in C, you surround the text with /* and then */ to block off everything between as a
comment. Certain compiler environments or text editorswill change the color of a commented area to
make it easier to spot, but some will not. Be certain not to accidentally comment out code (that is, to
tell the compiler part of your code is a comment) you need for the program.
When you are learning to program, it is also useful to comment out sections of code in order to see
how the output is affected.
Using Variables
It is also possible for your program to accept input. But first, before you try to receive input, you
must have a place to store that input. In programming, input and data are stored in variables. There
are several different types of variables; when you tell the compiler you are declaring a variable, you
must include the data type along with the name of the variable. Several basic types include char, int,
and float. Each type can store different types of data.
A variable of type char stores a single character, variables of type int store integers (numbers without
decimal places), and variables of type float store numbers with decimal places. Each of these
variable types - char, int, and float - is each a keyword that you use when you declare a variable.
Some variables also use more of the computer's memory to store their values.
It may seem strange to have multiple variable types when it seems like some variable types are
redundant. But using the right variable size can be important for making your program efficient
because some variables require more memory than others.
Before you can use a variable, you must tell the compiler about it by declaring it and telling the
compiler about what its "type" is. To declare a variable you use the syntax <variable type> <name of
variable>;. (The brackets here indicate that your replace the expression with text described within the
brackets.) For instance, a basic variable declaration might look like this:
int myVariable;
It is permissible to declare multiple variables of the same type on the same line; each one should be
separated by a comma. If you attempt to use an undefined variable, your program will not run, and
you will receive an error message informing you that you have made a mistake.
Here are some variable declaration examples:
int x;
26
int a, b, c, d;
char letter;
float the_float;
While you can have multiple variables of the same type, you cannot have multiple variables with the
same name. Moreover, you cannot have variables and functions with the same name.
A final restriction on variables is that variable declarations must come before other types of
statements in the given "code block" (a code block is just a segment of code surrounded by { and }).
So in C you must declare all of your variables before you do anything else:
Wrong
#include <stdio.h>
int main()
{
/* wrong! The variable declaration must appear first */
printf( "Declare x next" );
int x;
return 0;
}
Fixed
#include <stdio.h>
int main()
{
int x;
printf( "Declare x first" );
return 0;
}
Reading input
We'll be using the scanf function to read in a value and then printf to read it back out. Example:
#include <stdio.h>
int main()
{
int this_is_a_number;
printf( "Please enter a number: " );
scanf( "%d", &this_is_a_number );
printf( "You entered %d", this_is_a_number );
getchar();
27
return 0;
}
The io in stdio.h stands for "input/output"; std just stands for "standard.") The keyword int declares
this_is_a_number to be an integer.
The scanf function works by taking a string and some variables modified with &. The string tells
scanf what variables to look for: notice that we have a string containing only "%d" -- this tells the
scanf function to read in an integer. The second argument of scanf is the variable, sort of. We'll learn
more about what is going on later, but the gist of it is that scanf needs to know where the variable is
stored in order to change its value. Using & in front of a variable allows you to get its location and
give that to scanf instead of the value of the variable. The & gives the scanf function directions to the
variable.
When the program runs, each call to scanf checks its own input string to see what kinds of input to
expect, and then stores the value input into the variable.
The second printf statement also contains the same '%d'--both scanf and printf use the same format
for indicating values embedded in strings. In this case, printf takes the first argument after the string,
the variable this_is_a_number, and treats it as though it were of the type specified by the "format
specifier". In this case, printf treats this_is_a_number as an integer based on the format specifier.
So what does it mean to treat a number as an integer? If the user attempts to type in a decimal
number, it will be truncated (that is, the decimal component of the number will be ignored) when
stored in the variable.
C Operators
Of course, no matter what type you use, variables are uninteresting without the ability to modify
them. Several operators used with variables include the following: *, -, +, /, =, ==, >, <. The *
multiplies, the / divides, the - subtracts, and the + adds. It is of course important to realize that to
modify the value of a variable inside the program it is rather important to use the equal sign. In some
languages, the equal sign compares the value of the left and right values, but in C == is used for that
task. The equal sign is still extremely useful. It sets the value of the variable on the left side of the
equals sign equal to the value on the right side of the equals sign. The operators that perform
mathematical functions should be used on the right side of an equal sign in order to assign the result
to a variable on the left side.
Here are a few examples:
a = 4 * 6; /* (Note use of comments and of semicolon) a is 24 */
a = a + 5; /* a equals the original value of a with five added to it */
a == 5 /* Does NOT assign five to a. Rather, it checks to see if a equals 5.*/
28
The other form of equal, ==, is not a way to assign a value to a variable. Rather, it checks to see if
the variables are equal. It is extremely useful in many areas of C; for example, you will often use ==
in such constructions as conditional statements and loops. You can probably guess how < and >
function. They are greater than and less than operators.
For example:
a < 5 /* Checks to see if a is less than five */
a > 5 /* Checks to see if a is greater than five */
a == 5 /* Checks to see if a equals five, for good measure */
let us examine the meaning of TRUE and FALSE in computer terminology. A true statement is one
that evaluates to a nonzero number. A false statement evaluates to zero. When you perform
comparison with the relational operators, the operator will return 1 if the comparison is true, or 0 if
the comparison is false. For example, the check 0 == 2 evaluates to 0. The check 2 == 2 evaluates to
a 1.
Here are the relational operators, as they are known, along with examples:
> greater than 5 > 4 is TRUE
< less than 4 < 5 is TRUE
>= greater than or equal 4 >= 4 is TRUE
<= less than or equal 3 <= 4 is TRUE
== equal to 5 == 5 is TRUE
!= not equal to 5 != 4 is TRUE
Conditional Statements in C
The ability to control the flow of your program, letting it make decisions on what code to execute, is
valuable to the programmer.
1) If
The if statement allows you to control if a program enters a section of code or not based on whether a
given condition is true or false. One of the important functions of the if statement is that it allows the
program to select an action based upon the user's input. For example, by using an if statement to
check a user-entered password, your program can decide whether a user is allowed access to the
program.
Without a conditional statement such as the if statement, programs would run almost the exact same
way every time, always following the same sequence of function calls. If statements allow the flow
of the program to be changed, which leads to more interesting code.
Basic If Syntax
The structure of an if statement is as follows:
29
if ( statement is TRUE )
Execute this line of code
Here is a simple example that shows the syntax:
if ( 5 < 10 )
printf( "Five is now less than ten, that's a big surprise" );
Here, we're just evaluating the statement, "is five less than ten", to see if it is true or not; with any
luck, it is! If you want, you can write your own full program including stdio.h and put this in the
main function and run it to test.
To have more than one statement execute after an if statement that evaluates to true, use braces, like
we did with the body of the main function. Anything inside braces is called a compound statement,
or a block. When using if statements, the code that depends on the if statement is called the "body"
of the if statement.
For example:
if ( TRUE ) {
/* between the braces is the body of the if statement */
Execute all statements inside the body
}
2) Else
Sometimes when the condition in an if statement evaluates to false, it would be nice to execute some
code instead of the code executed when the statement evaluates to true. The "else" statement
effectively says that whatever code after it (whether a single line or code between brackets) is
executed if the if statement is FALSE.
It can look like this:
if ( TRUE ) {
/* Execute these statements if TRUE */
}
else {
/* Execute these statements if FALSE */
}
3) Else if
Another use of else is when there are multiple conditional statements that may all evaluate to true,
yet you want only one if statement's body to execute. You can use an "else if" statement following an
if statement and its body; that way, if the first statement is true, the "else if" will be ignored, but if
the if statement is false, it will then check the condition for the else if statement. If the if statement
30
was true the else statement will not be checked. It is possible to use numerous else if statements to
ensure that only one block of code is executed.example:
#include <stdio.h>
int main() /* Most important part of the program! */
{
int age; /* Need a variable... */
printf( "Please enter your age" ); /* Asks for age */
scanf( "%d", &age ); /* The input is put in age */
if ( age < 100 ) { /* If the age is less than 100 */
printf ("You are pretty young!n" ); /* Just to show you it works... */
}
else if ( age == 100 ) { /* I use else just to show an example */
printf( "You are oldn" );
}
else {
printf( "You are really oldn" ); /* Executed if no other statement is */
}
return 0;
}
Loops
Loops are used to repeat a block of code. Being able to have your program repeatedly execute a
block of code is one of the most basic but useful tasks in programming -- many programs or websites
that produce extremely complex output (such as a message board) are really only executing a single
task many times.a loop lets you write a very simple statement to produce a significantly greater result
simply by repetition.
1 ) For
for ( variable initialization; condition; variable update ) {
Code to execute while the condition is true
}
The variable initialization allows you to either declare a variable and give it a value or give a value to
an already existing variable. Second, the condition tells the program that while the conditional
expression is true the loop should continue to repeat itself. The variable update section is the easiest
way for a for loop to handle changing of the variable. It is possible to do things like x++, x = x + 10,
or even x = random ( 5 ), and if you really wanted to, you could call other functions that do nothing
to the variable but still have a useful effect on the code. A semicolon separates each of these sections,
that is important. Also note that every single one of the sections may be empty, though the
semicolons still have to be there. If the condition is empty, it is evaluated as true and the loop will
repeat until something else stops it.
Example:
31
#include <stdio.h>
int main()
{
int x;
/* The loop goes while x < 10, and x increases by one every loop*/
for ( x = 0; x < 10; x++ ) {
/* Keep in mind that the loop condition checks
the conditional statement before it loops again.
consequently, when x equals 10 the loop breaks.
x is updated before the condition is checked. */
printf( "%dn", x );
}
getchar();
This program is a very simple example of a for loop. x is set to zero, while x is less than 10 it calls
printf to display the value of the variable x, and it adds 1 to x until the condition is met. The variable
is incremented after the code in the loop is run for the first time.
2) While
While loops are very simple. The basic structure is while ( condition ) { Code to execute while the
condition is true } The true represents a boolean expression which could be x == 1 or while ( x != 7 )
(x does not equal 7). It can be any combination of boolean statements that are legal. Even, (while x
==5 || v == 7) which says execute the code while x equals five or while v equals 7. Notice that a
while loop is like a stripped-down version of a for loop-- it has no initialization or update section.
However, an empty condition is not legal for a while loop as it is with a for loop.
Example:
#include <stdio.h>
int main()
{
int x = 0; /* Don't forget to declare variables */
while ( x < 10 ) { /* While x is less than 10 */
printf( "%dn", x );
x++; /* Update x so the condition can be met eventually */
}
getchar();
}
This was another simple example, but it is longer than the above FOR loop. The easiest way to think
of the loop is that when it reaches the brace at the end it jumps back up to the beginning of the loop,
which checks the condition again and decides whether to repeat the block another time, or stop and
move to the next statement after the block.
32
3) Do while
do {
} while ( condition );
Notice that the condition is tested at the end of the block instead of the beginning, so the block will
be executed at least once. If the condition is true, we jump back to the beginning of the block and
execute it again. A do..while loop is almost the same as a while loop except that the loop body is
guaranteed to execute at least once. A while loop says "Loop while the condition is true, and execute
this block of code", a do..while loop says "Execute this block of code, and then continue to loop
while the condition is true".
Example:
#include <stdio.h>
int main()
{
int x;
x = 0;
do {
/* "Hello, world!" is printed at least one time
even though the condition is false */
printf( "Hello, world!n" );
} while ( x != 0 );
getchar();
}
Keep in mind that you must include a trailing semi-colon after the while in the above example. A
common error is to forget that a do..while loop must be terminated with a semicolon (the other loops
should not be terminated with a semicolon, adding to the confusion). Notice that this loop will
execute once, because it automatically executes before checking the condition.
Break and Continue
Two keywords that are very important to looping are break and continue. The break command will
exit the most immediately surrounding loop regardless of what the conditions of the loop are. Break
is useful if we want to exit a loop under special circumstances. For example:
while (true)
{
take_turn(player1);
take_turn(player2);
}
33
This will make the game alternate between having player 1 and player 2 take turns. The only
problem with this logic is that there's no way to exit the game; the loop will run forever! Let's try
something like this instead:
while(true)
{
if (someone_has_won() || someone_wants_to_quit() == TRUE)
{break;}
take_turn(player1);
if (someone_has_won() || someone_wants_to_quit() == TRUE)
{break;}
take_turn(player2);
}
This code accomplishes what we want--the primary loop of the game will continue under normal
circumstances, but under a special condition (winning or exiting) the flow will stop and our program
will do something else.
Continue is another keyword that controls the flow of loops. If you are executing a loop and hit a
continue statement, the loop will stop its current iteration, update itself (in the case of for loops) and
begin to execute again from the top.
Functions
A function is a group of statements that together perform a task. Every C program has at least one
function, which is main(), and all the most trivial programs can define additional functions. You
can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division is such that each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For
example, strcat() to concatenate two strings, memcpy() to copy one memory location to another
location, and many more functions.
A function can also be referred as a method or a sub-routine or a procedure, etc.
Defining aFunction
The general form of a function definition in C programming language is as follows –
return_type function_name( parameter list ) {
body of the function
}
A function definition in C programming consists of a function header and a function body. Here are
all the parts of a function −
34
 Return Type − A function may return a value. The return_type is the data type of the value
the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define what the
function does.
Example
Given below is the source code for a function called max(). This function takes two parameters
num1 and num2 and returns the maximum value between the two −
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Defining aFunction
A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.
35
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so the
following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you call that
function in another file. In such case, you should declare the function at the top of the file calling
the function.
Calling aFunction
While creating a C function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A called
function performs a defined task and when its return statement is executed or when its function-
ending closing brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name,
and if the function returns a value, then you can store the returned value. For example −
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
int ret;
36
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %dn", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments.
These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.
37
S.N. Call Type & Description
1 Call by value
This method copies the actual value of an argument into the formal parameter of
the function. In this case, changes made to the parameter inside the function have
no effect on the argument.
2 Call by reference
This method copies the address of an argument into the formal parameter. Inside
the function, the address is used to access the actual argument used in the call. This
means that changes made to the parameter affect the argument.
Switch case in C
Switch case statements are a substitute for long if statements that compare a variable to several
"integral" values ("integral" values are simply values that can be expressed as an integer, such as the
value of a char). The basic format for using switch case is outlined below. The value of the variable
given into switch is compared to the value following each of the cases, and when one value matches
the value of the variable, the computer continues executing the program from that point.
switch ( <variable> ) {
case this-value:
Code to execute if <variable> == this-value
break;
case that-value:
Code to execute if <variable> == that-value
break;
...
default:
Code to execute if <variable> does not equal the value following any of the cases
break;
}
The condition of a switch statement is a value. The case says that if it has the value of whatever is
after that case then do whatever follows the colon. The break is used to break out of the case
statements. Break is a keyword that breaks out of the code block, usually surrounded by braces,
which it is in. In this case, break prevents the program from falling through and executing the code in
all the other case statements. An important thing to note about the switch statement is that the case
values may only be constant integral expressions.
38
Blink Example In Arduino
Now after having studied about the hardware as well as the software,
A typical program for a beginning Arduino programmer blinks an LED repeatedly. This program
uses the functions pinMode, digitalWrite, and delay, which are provided by the internal libraries
included in the IDE environment. The program is usually loaded in the Arduino by the manufacturer.
Blink
Turns on an LED on for one second, then off for one second, repeatedly. Most Arduinos have an on-
board LED you can control. On the UNO, MEGA and ZERO it is attached to digital pin 13, on
MKR1000 on pin 6. LED_BUILTIN is set to the correct LED pin independent of which board is used.
Program Source Code:-
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
39

More Related Content

What's hot

Embedded system programming using Arduino microcontroller
Embedded system programming using Arduino microcontrollerEmbedded system programming using Arduino microcontroller
Embedded system programming using Arduino microcontroller
Arun Kumar
 
Introduction to Arduino Hardware and Programming
Introduction to Arduino Hardware and ProgrammingIntroduction to Arduino Hardware and Programming
Introduction to Arduino Hardware and Programming
Emmanuel Obot
 
Introduction to Arduino.pptx
Introduction to Arduino.pptxIntroduction to Arduino.pptx
Introduction to Arduino.pptx
Akshat Bijronia
 
Arduino seminar report
Arduino seminar reportArduino seminar report
Arduino seminar report
Zaka Jutt
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
Richard Rixham
 
Introduction to Raspberry PI
Introduction to Raspberry PIIntroduction to Raspberry PI
Introduction to Raspberry PI
Chandrashekar Babu
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
Green Moon Solutions
 
Embedded system design using arduino
Embedded system design using arduinoEmbedded system design using arduino
Embedded system design using arduino
Santosh Verma
 
Report on arduino
Report on arduinoReport on arduino
Report on arduino
Ravi Phadtare
 
arduino
 arduino arduino
arduino
jhcid
 
ESP8266 and IOT
ESP8266 and IOTESP8266 and IOT
ESP8266 and IOT
dega1999
 
Home Automation Using Arduino Uno and HC-05
Home Automation Using Arduino Uno and HC-05Home Automation Using Arduino Uno and HC-05
Home Automation Using Arduino Uno and HC-05
Vidhi Shah
 
Arduino uno
Arduino unoArduino uno
Arduino uno
creatjet3d labs
 
Difference Between CISC RISC, Harward & Von-neuman
Difference Between CISC RISC, Harward & Von-neumanDifference Between CISC RISC, Harward & Von-neuman
Difference Between CISC RISC, Harward & Von-neuman
Kailas Kharse
 
Introduction to ESP32 Programming [Road to RIoT 2017]
Introduction to ESP32 Programming [Road to RIoT 2017]Introduction to ESP32 Programming [Road to RIoT 2017]
Introduction to ESP32 Programming [Road to RIoT 2017]
Alwin Arrasyid
 
Arduino course
Arduino courseArduino course
Arduino course
Ahmed Shelbaya
 
Arduino Workshop Day 1 - Basic Arduino
Arduino Workshop Day 1 - Basic ArduinoArduino Workshop Day 1 - Basic Arduino
Arduino Workshop Day 1 - Basic Arduino
Vishnu
 
Arduino based heartbeat monitoring system.
Arduino based heartbeat monitoring system.Arduino based heartbeat monitoring system.
Arduino based heartbeat monitoring system.
Arkadeep Dey
 
Heart beat detector using arduino
Heart beat detector using arduinoHeart beat detector using arduino
Heart beat detector using arduino
Varshaa Khandagale
 

What's hot (20)

Embedded system programming using Arduino microcontroller
Embedded system programming using Arduino microcontrollerEmbedded system programming using Arduino microcontroller
Embedded system programming using Arduino microcontroller
 
Introduction to Arduino Hardware and Programming
Introduction to Arduino Hardware and ProgrammingIntroduction to Arduino Hardware and Programming
Introduction to Arduino Hardware and Programming
 
Introduction to Arduino.pptx
Introduction to Arduino.pptxIntroduction to Arduino.pptx
Introduction to Arduino.pptx
 
Arduino seminar report
Arduino seminar reportArduino seminar report
Arduino seminar report
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
 
Introduction to Raspberry PI
Introduction to Raspberry PIIntroduction to Raspberry PI
Introduction to Raspberry PI
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
 
Embedded system design using arduino
Embedded system design using arduinoEmbedded system design using arduino
Embedded system design using arduino
 
Report on arduino
Report on arduinoReport on arduino
Report on arduino
 
arduino
 arduino arduino
arduino
 
ESP8266 and IOT
ESP8266 and IOTESP8266 and IOT
ESP8266 and IOT
 
Home Automation Using Arduino Uno and HC-05
Home Automation Using Arduino Uno and HC-05Home Automation Using Arduino Uno and HC-05
Home Automation Using Arduino Uno and HC-05
 
Arduino uno
Arduino unoArduino uno
Arduino uno
 
Difference Between CISC RISC, Harward & Von-neuman
Difference Between CISC RISC, Harward & Von-neumanDifference Between CISC RISC, Harward & Von-neuman
Difference Between CISC RISC, Harward & Von-neuman
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
 
Introduction to ESP32 Programming [Road to RIoT 2017]
Introduction to ESP32 Programming [Road to RIoT 2017]Introduction to ESP32 Programming [Road to RIoT 2017]
Introduction to ESP32 Programming [Road to RIoT 2017]
 
Arduino course
Arduino courseArduino course
Arduino course
 
Arduino Workshop Day 1 - Basic Arduino
Arduino Workshop Day 1 - Basic ArduinoArduino Workshop Day 1 - Basic Arduino
Arduino Workshop Day 1 - Basic Arduino
 
Arduino based heartbeat monitoring system.
Arduino based heartbeat monitoring system.Arduino based heartbeat monitoring system.
Arduino based heartbeat monitoring system.
 
Heart beat detector using arduino
Heart beat detector using arduinoHeart beat detector using arduino
Heart beat detector using arduino
 

Similar to Winter traning arduino report final

What are the different types of arduino boards
What are the different types of arduino boardsWhat are the different types of arduino boards
What are the different types of arduino boards
elprocus
 
Arduino Programming Software Development
Arduino Programming Software DevelopmentArduino Programming Software Development
Arduino Programming Software Development
Sanjay Kumar
 
ARDUINO OVERVIEW HARDWARE SOFTWARE AND INSTALLATION.pptx
ARDUINO OVERVIEW HARDWARE  SOFTWARE AND INSTALLATION.pptxARDUINO OVERVIEW HARDWARE  SOFTWARE AND INSTALLATION.pptx
ARDUINO OVERVIEW HARDWARE SOFTWARE AND INSTALLATION.pptx
menchc1207
 
Our arduino project
Our arduino projectOur arduino project
Our arduino project
Albaserra2005
 
ARDUINO OVERVIEW HARDWARE SOFTWARE AND INSTALLATION.pdf
 ARDUINO OVERVIEW HARDWARE  SOFTWARE AND INSTALLATION.pdf ARDUINO OVERVIEW HARDWARE  SOFTWARE AND INSTALLATION.pdf
ARDUINO OVERVIEW HARDWARE SOFTWARE AND INSTALLATION.pdf
Ruby Hermano
 
WORKING PRINCIPLE OF ARDUINO AND USING IT AS A TOOL FOR STUDY AND RESEARCH
WORKING PRINCIPLE OF ARDUINO AND USING IT AS A TOOL FOR STUDY AND RESEARCHWORKING PRINCIPLE OF ARDUINO AND USING IT AS A TOOL FOR STUDY AND RESEARCH
WORKING PRINCIPLE OF ARDUINO AND USING IT AS A TOOL FOR STUDY AND RESEARCH
ijdpsjournal
 
Interoperability in Internet of Things (IOT)
Interoperability in Internet of Things (IOT)Interoperability in Internet of Things (IOT)
Interoperability in Internet of Things (IOT)
manditalaskar123
 
Arduino Development For Beginners
Arduino Development For BeginnersArduino Development For Beginners
Arduino Development For Beginners
FTS seminar
 
android app based home automation
android app based home automationandroid app based home automation
android app based home automationAshikur Rahman
 
Arduino
ArduinoArduino
Arduino
Ankit Sharma
 
Advanced View Arduino Projects List - Use Arduino for Projects.pdf
Advanced View Arduino Projects List - Use Arduino for Projects.pdfAdvanced View Arduino Projects List - Use Arduino for Projects.pdf
Advanced View Arduino Projects List - Use Arduino for Projects.pdf
WiseNaeem
 
Arduino
ArduinoArduino
Arduino
VigneshABME
 
Introduction to Arduino
Introduction to Arduino Introduction to Arduino
Introduction to Arduino
Dennis Espiritu
 
Arduino mario y jimena
Arduino mario y jimenaArduino mario y jimena
Arduino mario y jimena
marienafuerez
 
Arduino
ArduinoArduino
Arduino presentation by_warishusain
Arduino presentation by_warishusainArduino presentation by_warishusain
Arduino presentation by_warishusain
student
 
Introduction to arduino
Introduction to arduinoIntroduction to arduino
Introduction to arduino
Mohamed Essam
 
Up and running with Arduino
Up and running with Arduino Up and running with Arduino
Up and running with Arduino
KUET
 
Arduino: Tutorial de Arduino
Arduino: Tutorial de ArduinoArduino: Tutorial de Arduino
Arduino: Tutorial de Arduino
SANTIAGO PABLO ALBERTO
 
Arduino Open Source Report guia de e 202.pdf
Arduino Open Source Report guia de e 202.pdfArduino Open Source Report guia de e 202.pdf
Arduino Open Source Report guia de e 202.pdf
AbrahamSantos31
 

Similar to Winter traning arduino report final (20)

What are the different types of arduino boards
What are the different types of arduino boardsWhat are the different types of arduino boards
What are the different types of arduino boards
 
Arduino Programming Software Development
Arduino Programming Software DevelopmentArduino Programming Software Development
Arduino Programming Software Development
 
ARDUINO OVERVIEW HARDWARE SOFTWARE AND INSTALLATION.pptx
ARDUINO OVERVIEW HARDWARE  SOFTWARE AND INSTALLATION.pptxARDUINO OVERVIEW HARDWARE  SOFTWARE AND INSTALLATION.pptx
ARDUINO OVERVIEW HARDWARE SOFTWARE AND INSTALLATION.pptx
 
Our arduino project
Our arduino projectOur arduino project
Our arduino project
 
ARDUINO OVERVIEW HARDWARE SOFTWARE AND INSTALLATION.pdf
 ARDUINO OVERVIEW HARDWARE  SOFTWARE AND INSTALLATION.pdf ARDUINO OVERVIEW HARDWARE  SOFTWARE AND INSTALLATION.pdf
ARDUINO OVERVIEW HARDWARE SOFTWARE AND INSTALLATION.pdf
 
WORKING PRINCIPLE OF ARDUINO AND USING IT AS A TOOL FOR STUDY AND RESEARCH
WORKING PRINCIPLE OF ARDUINO AND USING IT AS A TOOL FOR STUDY AND RESEARCHWORKING PRINCIPLE OF ARDUINO AND USING IT AS A TOOL FOR STUDY AND RESEARCH
WORKING PRINCIPLE OF ARDUINO AND USING IT AS A TOOL FOR STUDY AND RESEARCH
 
Interoperability in Internet of Things (IOT)
Interoperability in Internet of Things (IOT)Interoperability in Internet of Things (IOT)
Interoperability in Internet of Things (IOT)
 
Arduino Development For Beginners
Arduino Development For BeginnersArduino Development For Beginners
Arduino Development For Beginners
 
android app based home automation
android app based home automationandroid app based home automation
android app based home automation
 
Arduino
ArduinoArduino
Arduino
 
Advanced View Arduino Projects List - Use Arduino for Projects.pdf
Advanced View Arduino Projects List - Use Arduino for Projects.pdfAdvanced View Arduino Projects List - Use Arduino for Projects.pdf
Advanced View Arduino Projects List - Use Arduino for Projects.pdf
 
Arduino
ArduinoArduino
Arduino
 
Introduction to Arduino
Introduction to Arduino Introduction to Arduino
Introduction to Arduino
 
Arduino mario y jimena
Arduino mario y jimenaArduino mario y jimena
Arduino mario y jimena
 
Arduino
ArduinoArduino
Arduino
 
Arduino presentation by_warishusain
Arduino presentation by_warishusainArduino presentation by_warishusain
Arduino presentation by_warishusain
 
Introduction to arduino
Introduction to arduinoIntroduction to arduino
Introduction to arduino
 
Up and running with Arduino
Up and running with Arduino Up and running with Arduino
Up and running with Arduino
 
Arduino: Tutorial de Arduino
Arduino: Tutorial de ArduinoArduino: Tutorial de Arduino
Arduino: Tutorial de Arduino
 
Arduino Open Source Report guia de e 202.pdf
Arduino Open Source Report guia de e 202.pdfArduino Open Source Report guia de e 202.pdf
Arduino Open Source Report guia de e 202.pdf
 

Recently uploaded

Steel & Timber Design according to British Standard
Steel & Timber Design according to British StandardSteel & Timber Design according to British Standard
Steel & Timber Design according to British Standard
AkolbilaEmmanuel1
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Fundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptxFundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptx
manasideore6
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABSDESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
itech2017
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 

Recently uploaded (20)

Steel & Timber Design according to British Standard
Steel & Timber Design according to British StandardSteel & Timber Design according to British Standard
Steel & Timber Design according to British Standard
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Fundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptxFundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptx
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABSDESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
DESIGN AND ANALYSIS OF A CAR SHOWROOM USING E TABS
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 

Winter traning arduino report final

  • 1. 1 WINTER TRAINING PROJECT ON "ARDUINO WITH C PROGRAMMING" Guru Tegh Bahadur Institute Of Technology G-8 Area, Rajouri Garden, New Delhi 110064 Submitted By: Govind Jha
  • 2. 2 Acknowledgement I have taken efforts in this winter training. However, it would not have been possible without the kind support and help of many individuals and organizations. I would like to extend my sincere thanks to all of them. I am highly indebted to PhD. Ian G. Harris for his guidance and constant supervision as well as for providing necessary information regarding the training & also for his support in completing the project. I would like to express my gratitude towards my parents & members of university of California, Irvine for their kind co-operation and encouragement which helped me in completion of this training. I would like to express my special gratitude and thanks to coursera for giving me an opportunity to access the course material. My thanks and appreciations also go to my colleague in developing the report and people who have willingly helped me out with their abilities.
  • 3. 3 Contents 1. Introduction to Arduino ………………………………………………4 2. Advantages of Arduino platform……………………………………...5 3. Arduino Hardware…………………………………………………….6 4. Arduino Board Schematic Representation……………………………7  Components  Digital Pins  Analog Pins  Power Pins  Other Pins 5. Arduino Shields……………………………………………………….11  Prototyping  Ethernet, Wi-Fi, Wireless, GPS, Etc.  Music and Sound  Displays and Cameras  Motor Drivers 6. Arduino UNO…………………………………………………………17  Pin Description  Arduino UNO Schematics 7. Arduino Software Development………………………………………20  Arduino IDE  Writing Sketches  Arduino libraries  Standard Libraries 8. C Programming Language in Arduino………………………………..23
  • 4. 4 9. Explaining your Code……………………………………………..24  Using Variables 10. C Operators………………………………………………………26 11. Conditional Statements in C……………………………………..27  If  If else  If else if 12. Loops…………………………………………………………….29  For loop  Do loop  Do while loop 13. Break and Continue……………………………………………...31 14. Functions………………………………………………………...32  Defining a Function  Defining a Function  Calling a Function  Function Arguments 15. Switch case in C…………………………………………………36 16. Blink Example In Arduino ……………………………………...37
  • 5. 5 Introduction to Arduino Platform Arduino is an open-source computer hardware and software platform for building digital devices and interactive objects that can sense and control the digital world around them. For example, Arduino boards are able to read inputs - light on a sensor, a finger on a button, or a Twitter message - and turn it into an output - activating a motor, turning on an LED, publishing something online. You can tell your board what to do by sending a set of instructions to the microcontroller on the board. To do so you use the Arduino programming language (based on Wiring), and the Arduino Software (IDE), based on Processing. Thus, Arduino platform works in terms of the physical board and the libraries and the IDE (integrated development environment). Arduino board designs use a variety of microprocessors and controllers. The boards are equipped with sets of digital and analog input/output (I/O) pins that may be interfaced to various expansion boards (shields) and other circuits. The boards feature serial communications interfaces, including Universal Serial Bus (USB) on some models, which are also used for loading programs from personal computers. The microcontrollers are typically programmed using a dialect of features from the programming languages C and C++. In addition to using traditional compiler tool chains, the Arduino project provides an integrated development environment (IDE) based on the Processing language project. Over the years Arduino has been the brain of thousands of projects, from everyday objects to complex scientific instruments. A worldwide community of makers - students, hobbyists, artists, programmers, and professionals - has gathered around this open-source platform, their contributions have added up to an incredible amount of accessible knowledge that can be of great help to novices and experts alike.
  • 6. 6 Advantages of Arduino Arduino is an open source, computer hardware and software company, project, and user community that designs and manufactures microcontroller kits for building digital devices and interactive objects that can sense and control objects in the physical world. The project's products are distributed as open-source hardware and software, which are licensed under the GNU Lesser General Public License (LGPL) or the GNU General Public License (GPL),[1] permitting the manufacture of Arduino boards and software distribution by anyone. Arduino boards are available commercially in preassembled form, or as do-it-yourself kits. Arduino was born at the Ivrea Interaction Design Institute as an easy tool for fast prototyping, aimed at students without a background in electronics and programming. As soon as it reached a wider community, the Arduino board started changing to adapt to new needs and challenges, differentiating its offer from simple 8-bit boards to products for IoT applications, wearable, 3D printing, and embedded environments. All Arduino boards are completely open-source, empowering users to build them independently and eventually adapt them to their particular needs. The software, too, is open- source, and it is growing through the contributions of users worldwide. Thanks to its simple and accessible user experience, Arduino has been used in innumerable different projects and applications. The Arduino software is easy-to-use for beginners, yet flexible enough for advanced users. It runs on Mac, Windows, and Linux. Teachers and students use it to build low cost scientific instruments, to prove chemistry and physics principles, or to get started with programming and robotics. Designers and architects build interactive prototypes, musicians and artists use it for installations and to experiment with new musical instruments. Makers, of course, use it to build many of the projects exhibited at the Maker Faire, for example. Arduino is a key tool to learn new things. Anyone - children, hobbyists, artists, programmers - can start tinkering just following the step by step instructions of a kit, or sharing ideas online with other members of the Arduino community.  Inexpensive - Arduino boards are relatively inexpensive compared to other microcontroller platforms. The least expensive version of the Arduino module can be assembled by hand, and even the pre-assembled Arduino modules cost less than $50  Cross-platform - The Arduino Software (IDE) runs on Windows, Macintosh OSX, and Linux operating systems. Most microcontroller systems are limited to Windows.  Simple, clear programming environment - The Arduino Software (IDE) is easy-to-use for beginners, yet flexible enough for advanced users to take advantage of as well. For teachers, it's conveniently based on the Processing programming environment, so students learning to program in that environment will be familiar with how the Arduino IDE works.  Open source and extensible software - The Arduino software is published as open source tools, available for extension by experienced programmers. The language can be expanded through C++ libraries, and people wanting to understand the technical details can make the leap from Arduino to the AVR C programming language on which it's based. Similarly, you can add AVR-C code directly into your Arduino programs if you want to.  Open source and extensible hardware - The plans of the Arduino boards are published under a Creative Commons license, so experienced circuit designers can make their own version of the module, extending it and improving it. Even relatively inexperienced users can build the breadboard version of the module in order to understand how it works and save money.
  • 7. 7 Arduino Hardware Arduino is open-source hardware. Most Arduino boards consist of an Atmel 8-bit AVR microcontroller (ATmega8, ATmega168, ATmega328, ATmega1280, ATmega2560) with varying amounts of flash memory, pins, and features. The 32-bit Arduino Due, based on the Atmel SAM3X8E was introduced in 2012. The boards use single or double-row pins or female headers that facilitate connections for programming and incorporation into other circuits. These may connect with add-on modules termed shields. Multiple, and possibly stacked shields may be individually addressable via an I²C serial bus. Most boards include a 5 V linear regulator and a 16 MHz crystal oscillator or ceramic resonator. Some designs, such as the Lily Pad, run at 8 MHz and dispense with the on board voltage regulator due to specific form-factor restrictions. Arduino microcontrollers are pre-programmed with a boot loader that simplifies uploading of programs to the on-chip flash memory. The default boot loader of the Aduino UNO is the opt boot loader. Boards are loaded with program code via a serial connection to another computer. Some serial Arduino boards contain a level shifter circuit to convert between RS-232 logic levels and transistor–transistor logic (TTL) level signals. Current Arduino boards are programmed via Universal Serial Bus (USB), implemented using USB-to-serial adapter chips such as the FTDI FT232. Some boards, such as later-model Uno boards, substitute the FTDI chip with a separate AVR chip containing USB-to-serial firmware, which is reprogrammable via its own ICSP header. Other variants, such as the Arduino Mini and the unofficial Boarduino, use a detachable USB-to-serial adapter board or cable, Bluetooth or other methods, when used with traditional microcontroller tools instead of the Arduino IDE, standard AVR in-system programming (ISP) programming is used. The Arduino board exposes most of the microcontroller's I/O pins for use by other circuits. The Diecimila, Duemilanove, and current Uno provide 14 digital I/O pins, six of which can produce pulse-width modulated signals, and six analog inputs, which can also be used as six digital I/O pins. These pins are on the top of the board, via female 0.1-inch (2.54 mm) headers. Several plug-in application shields are also commercially available. The Arduino Nano, and Arduino- compatible Bare Bones Board and Boarduino boards may provide male header pins on the underside of the board that can plug into solderless breadboards. Many Arduino-compatible and Arduino-derived boards exist. Some are functionally equivalent to an Arduino and can be used interchangeably. Many enhance the basic Arduino by adding output drivers, often for use in school-level education, to simplify making buggies and small robots. Others are electrically equivalent but change the form factor, sometimes retaining compatibility with shields, sometimes not. Some variants use different processors, of varying compatibility.
  • 8. 8 Arduino Boards The original Arduino hardware was produced by the Italian company Smart Projects. Some Arduino- branded boards have been designed by the American companies SparkFun Electronics and Adafruit Industries. As of 2016, 17 versions of the Arduino hardware have been commercially produced. Some of the Arduino boards are:  Arduino RS232  Arduino Diecimila  Arduino Duemilanove  Arduino Uno R2  Arduino Uno SMD R3  Arduino Leonardo  Arduino Pro  Arduino LilyPad 00  Arduino Mega  Arduino Nano  Arduino Robot  Arduino Esplora  Arduino Ethernet  Arduino Yun  Arduino Due Arduino Uno R2 Arduino LilyPad 00
  • 9. 9 Arduino Nano Arduino Yun Arduino Diecimila Arduino Uno R2 Arduino Mega Arduino Leonardo
  • 10. 10 Arduino Board Schematic Representation Components:-  Analog Reference pin (orange)  Digital Ground (light green)  Digital Pins 2-13 (green)  Digital Pins 0-1/Serial In/Out - TX/RX (dark green) - These pins cannot be used for digital i/o (digitalRead and digitalWrite) if you are also using serial communication (e.g. Serial.begin).  Reset Button - S1 (dark blue)  In-circuit Serial Programmer (blue-green)  Analog In Pins 0-5 (light blue)  Power and Ground Pins (power: orange, grounds: light orange)  External Power Supply In (9-12VDC) - X1 (pink)  Toggles External Power and USB Power (place jumper on two pins closest to desired supply) - SV1 (purple)  USB (used for uploading sketches to the board and for serial communication between the board and the computer; can be used to power the board) (yellow) Digital Pins In addition to the specific functions listed below, the digital pins on an Arduino board can be used for general purpose input and output via the pinMode(), digitalRead(), and digitalWrite() commands. Each pin has an internal pull-up resistor which can be turned on and off using digitalWrite() (w/ a value of HIGH or LOW, respectively) when the pin is configured as an input. The maximum current per pin is 40 mA.
  • 11. 11  Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. On the Arduino Diecimila, these pins are connected to the corresponding pins of the FTDI USB-to-TTL Serial chip. On the Arduino BT, they are connected to the corresponding pins of the WT11 Bluetooth module. On the Arduino Mini and LilyPad Arduino, they are intended for use with an external TTL serial module (e.g. the Mini-USB Adapter).  External Interrupts: 2 and 3. These pins can be configured to trigger an interrupt on a low value, a rising or falling edge, or a change in value. See the attachInterrupt() function for details.  PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output with the analogWrite() function. On boards with an ATmega8, PWM output is available only on pins 9, 10, and 11.  BT Reset: 7. (Arduino BT-only) Connected to the reset line of the bluetooth module.  SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication, which, although provided by the underlying hardware, is not currently included in the Arduino language.  LED: 13. On the Diecimila and LilyPad, there is a built-in LED connected to digital pin 13. When the pin is HIGH value, the LED is on, when the pin is LOW, it's off. Analog Pins In addition to the specific functions listed below, the analog input pins support 10-bit analog-to- digital conversion (ADC) using the analogRead() function. Most of the analog inputs can also be used as digital pins: analog input 0 as digital pin 14 through analog input 5 as digital pin 19. Analog inputs 6 and 7 (present on the Mini and BT) cannot be used as digital pins.  I2C: 4 (SDA) and 5 (SCL). Support I2C (TWI) communication using the Wire library (documentation on the Wiring website). Power Pins  VIN (sometimes labelled "9V"). The input voltage to the Arduino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin. Note that different boards accept different input voltages ranges, please see the documentation for your board. Also note that the LilyPad has no VIN pin and accepts only a regulated input.  5V. The regulated power supply used to power the microcontroller and other components on the board. This can come either from VIN via an on-board regulator, or be supplied by USB or another regulated 5V supply.  3V3. (Diecimila-only) A 3.3 volt supply generated by the on-board FTDI chip.  GND. Ground pins. Other Pins  AREF. Reference voltage for the Analog inputs. Not currently supported by the Arduino software.  Reset. (Diecimila-only) Bring this line LOW to reset the microcontroller. Typically used to add a reset button to shields which block the one on the board.
  • 12. 12 Arduino Shields Arduino and Arduino-compatible boards use printed circuit expansion boards called shields, Shields are boards that can be plugged on top of the Arduino PCB extending its capabilities. The different shields follow the same philosophy as the original toolkit: they are easy to mount, and cheap to produce. Shields can provide motor controls for 3D printing and other applications, Global Positioning System (GPS), Ethernet, liquid crystal display (LCD), or bread boarding (prototyping). Several shields can also be made do it yourself (DIY) Many Arduino shields are stackable. You can connect many shields together to create a “Big Mac” of Arduino modules. You could, for example, combine an Arduino Uno with a Voice Box Shield, and a WiFly Shield to create a WiFi Talking Stephen Hawking. Shields are often supplied with either an example sketch, or a library. So, not only do they just simply plug into your Arduino, but all you need to do to make them work is upload up some example code to the Arduino. Every Arduino shield must have the same form-factor as the standard Arduino. Power and ground pins on one eight (previously six) pin header, and analog pins on a six-pin header next to that. Digital pins cover the other edge on the other side, an eight-pin header separated from a 10-pin by that weird 0.5" spacing. Some shields also require a connection to the Arduino’s ICSP header (the 2x3 programming header on the end).
  • 13. 13 Some shields use every pin on the Arduino, while others only use a couple. When stacking shields, it’s important to make sure they don’t use overlapping pins. Some shields communicate with the Arduino via SPI, I2C, or Serial, and others use the Arduino’s interrupts or analog inputs. Prototyping Prototyping shields don’t add much functionality to the Arduino, but they do help in other ways. These shields might do something as simple as breaking out the Arduino pins to screw terminals. In general they make wiring to the Arduino easier.  ProtoShield Kit - The self-titled star of this category. This shield is basically a big prototyping area. You can stick a mini-breadboard on top, or just solder directly to the shield’s prototyping area.
  • 14. 14  ProtoScrew Shield - Like the ProtoShield, but each pin is also broken out to a screw terminal. Handy for connecting to external motors or heavy-duty sensors.  Go-Between Shield - The intention of this shield is to sit in between two shields. It swaps the pins of the top shield, so they don’t interfere with each other.  LiPower Shield - This shield allows you to power your Arduino with a Lithium Polymer battery.  Danger Shield - The most awesomest shield evar! This shield is a crazy conglomeration of displays, potentiometers, and other sensors. Great for learning the ins and outs of Arduino or incorporating into audio mixing projects.  Joystick Shield Kit - This makes your Arduino a bare-bones controller. With a joystick and four buttons, this makes for a great robot controller.  microSD Shield - The Arduino has limited storage space, but this easy-to-use shield (along with the SD library) allow for plenty of extra storage. Ethernet, WiFi, Wireless, GPS, Etc.  Arduino Ethernet Shield - This is one of the more classic shields. The Ethernet Shield supplies your Arduino with an ability to connect to the World Wide Web. There’s a great library to support it as well.
  • 15. 15  WiFly Shield - SparkFun’s WiFi Shield mainstay, this shield equips your Arduino with the ability to connect to 802.11b/g wireless networks. Then it can act as either a web server, client, or both.  Arduino Wi-Fi Shield - This is the Arduino Ethernet Shield sans wires. This shield can get your Arduino connected to a WiFi router, so it can host webpages and scour the Internet.  Electric Imp Shield - Electric Imp is a unique WiFi module, which looks like an SD card, but it packs a powerful cloud-based WiFi controller. This is probably the least expensive WiFi-enabling Arduino shield.  XBee Shield - XBee’s won’t get you connected to the Internet, but they do provide a solid, cheap means for communicating wirelessly. You could use an XBee to wirelessly trigger coffee machines, sprinklers, lights, or other household appliances.  Cellular Shield w/ SM5100B - Turn your Arduino into a cellular phone! Send SMS text messages, or hook up a microphone and speaker and use it to replace your iPhone.  GPS Shield - GPS isn’t as complicated as you might think. With a GPS Shield, your Arduino will always know where it is. Music and Sound  MP3 Player Shield - Turn your Arduino into an MP3 player. Just plug in a µSD card, add some speakers, upload the example code, and you can make your very own MP3 Playing Music Box
  • 16. 16  Music Instrument Shield - Use the MIDI protocol to turn your Arduino into a bank of musical instruments. It can make drums, piano, woodwinds, brass, and all sorts of other sound effects.  Spectrum Shield - The Spectrum Shield listens to audio, and sorts it into bins of different frequencies. Use it to make a nifty graphic equalizer display.  VoiceBox Shield - Give your Arduino a mechanical, robotic voice. Displays and Cameras  Color LCD Shield - Equip your Arduino with a unique 128x128 cellular phone color LCD.  EL Escudo - Electroluminescent wire is awesome! Use this shield to add up to eight strands of EL wire to your project. You can finally make that Arduino-powered Tron costume.
  • 17. 17  CMUcam - This camera module adds vision to your Arduino. You can use it to track blobs, so your robot doesn’t hit any traffic cones. Motor Drivers  Ardumoto Motor Driver Shield - This classic motor driver shield can control two DC motors.  Monster Moto Shield - If you need to drive beefier motors than the Ardumoto Shield can handle, this is the next step up.  PWM Shield - Usually when you think pulse-width modulation (PWM), you might think “dimming LEDs”, but PWM is also used to drive servo motors. This shield can be used to drive your crazy 12-servo hexapod.
  • 18. 18 Arduino UNO Arduino/Genuino Uno is a microcontroller board based on the ATmega328P (datasheet). It has 14 digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16 MHz quartz crystal, a USB connection, a power jack, an ICSP header and a reset button. It contains everything needed to support the microcontroller; simply connect it to a computer with a USB cable or power it with a AC-to-DC adapter or battery to get started. The Uno differs from all preceding boards in that it does not use the FTDI USB-to-serial driver chip. Instead, it features the Atmega8U2 programmed as a USB-to-serial converter "Uno" means one in Italian and was chosen to mark the release of Arduino Software (IDE) 1.0. The Uno board and version 1.0 of Arduino Software (IDE) were the reference versions of Arduino, now evolved to newer releases. The Uno board is the first in a series of USB Arduino boards, and the reference model for the Arduino platform.
  • 19. 19 Pin Description Input and Output Each of the 14 digital pins on the Arduino Uno can be used as an input or output, using pinMode(), digitalWrite(), and digitalRead() functions. They operate at 5 volts. Each pin can provide or receive a maximum of 40 mA and has an internal pull-up resistor (disconnected by default) of 20-50 kOhms. In addition, some pins have specialized functions: Serial: pins 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. These pins are connected to the corresponding pins of the ATmega8U2 USB-to-TTL Serial chip. External Interrupts: pins 2 and 3. These pins can be configured to trigger an interrupt on a low value, a rising or falling edge, or a change in value. See the attachInterrupt() function for details. PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output with the analogWrite() function. SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication using the SPI library. LED: 13. There is a built-in LED connected to digital pin 13. When the pin is HIGH value, the LED is on, when the pin is LOW, it’s off. The Uno has 6 analog inputs, labeled A0 through A5, each of which provide 10 bits of resolution (i.e. 1024 different values). By default they measure from ground to 5 volts, though is it possible to change the upper end of their range using the AREF pin and the analogReference() function. Additionally, some pins have specialized functionality: TWI: A4 or SDA pin and A5 or SCL pin. Support TWI communication using the Wire library. There are a couple of other pins on the board: AREF. Reference voltage for the analog inputs. Used with analogReference(). Reset. Bring this line LOW to reset the microcontroller. Typically used to add a reset button to shields which block the one on the board.
  • 20. 20 Arduino UNO Schematics Schematics are a traditional way to convey the hardware designs.its a diagram of what components are on the device and how they are wired together. They are used for implementing and wiring the components together which are present on the standard arduino chip.the arduino designs are open source ,so hardware schematics are also open source.with the help of the]is you can design your own circuit.
  • 21. 21 Arduino Software Development A program for Arduino may be written in any programming language for a compiler that produces binary machine code for the target processor. Atmel provides a development environment for their microcontrollers, AVR Studio and the newer Atmel Studio.[39][40][41] The Arduino project provides the Arduino integrated development environment (IDE), which is a cross-platform application written in the programming language Java. It originated from the IDE for the languages Processing and Wiring. It includes a code editor with features such as text cutting and pasting, searching and replacing text, automatic indenting, brace matching, and syntax highlighting, and provides simple one-click mechanisms to compile and upload programs to an Arduino board. It also contains a message area, a text console, a toolbar with buttons for common functions and a hierarchy of operation menus. The Arduino IDE supports the languages C and C++ using special rules of code structuring. The Arduino IDE supplies a software library from the Wiring project, which provides many common input and output procedures. User-written code only requires two basic functions, for starting the sketch and the main program loop, that are compiled and linked with a program stub main() into an executable cyclic executive program with the GNU toolchain, also included with the IDE distribution. The Arduino IDE employs the program avrdude to convert the executable code into a text file in hexadecimal encoding that is loaded into the Arduino board by a loader program in the board's firmware. Arduino IDE The Arduino Integrated Development Environment - or Arduino Software (IDE) - contains a text editor for writing code, a message area, a text console, a toolbar with buttons for common functions and a series of menus. It connects to the Arduino and Genuino hardware to upload programs and communicate with them.
  • 22. 22 Writing Sketches Programs written using Arduino Software (IDE) are called sketches. These sketches are written in the text editor and are saved with the file extension .ino. The editor has features for cutting/pasting and for searching/replacing text. The message area gives feedback while saving and exporting and also displays errors. The console displays text output by the Arduino Software (IDE), including complete error messages and other information. The bottom righthand corner of the window displays the configured board and serial port. The toolbar buttons allow you to verify and upload programs, create, open, and save sketches, and open the serial monitor.  Verify Checks your code for error while compiling it.  Upload Compiles your code and uploads it to the configured board. See uploading below for details.  New Creates a new sketch.
  • 23. 23  Open Presents a menu of all the sketches in your sketchbook. Clicking one will open it within the current window overwriting its content.  Save Saves your sketch.  Serial monitor Opens the serial monitor. Additional commands are found within the five menus: File, Edit, Sketch, Tools, Help. The menus are context sensitive, which means only those items relevant to the work currently being carried out are available. Arduino libraries Libraries provide extra functionality for use in sketches, e.g. working with hardware or manipulating data. To use a library in a sketch, select it from the Sketch > Import Library menu. This will insert one or more #include statements at the top of the sketch and compile the library with your sketch. Because libraries are uploaded to the board with your sketch, they increase the amount of space it takes up. If a sketch no longer needs a library, simply delete its #includestatements from the top of your code. The Arduino environment can be extended through the use of libraries, just like most programming platforms. Libraries provide extra functionality for use in sketches, e.g. working with hardware or manipulating data. To use a library in a sketch, select it from Sketch > Import Library. A number of libraries come installed with the IDE, but you can also download or create your own. Standard Libraries  EEPROM - reading and writing to "permanent" storage  Ethernet / Ethernet 2 - for connecting to the internet using the Arduino Ethernet Shield, Arduino Ethernet Shield 2 and Arduino Leonardo ETH  Firmata - for communicating with applications on the computer using a standard serial protocol.  GSM - for connecting to a GSM/GRPS network with the GSM shield.  Liquid Crystal - for controlling liquid crystal displays (LCDs)  SD - for reading and writing SD cards  Servo - for controlling servo motors  SPI - for communicating with devices using the Serial Peripheral Interface (SPI) Bus  Software Serial - for serial communication on any digital pins. Version 1.0 and later of Arduino incorporate Mikal Hart's New SoftSerial library as Software Serial.  Stepper - for controlling stepper motors  TFT - for drawing text , images, and shapes on the Arduino TFT screen  WiFi - for connecting to the internet using the Arduino WiFi shield
  • 24. 24 C Programming Language in Arduino Every full C program begins inside a function called "main". A function is simply a collection of commands that do "something". The main function is always called when the program first executes. From main, we can call other functions, whether they be written by us or by others or use built-in language features. To access the standard functions that comes with your compiler, you need to include a header with the #include directive. What this does is effectively take everything in the header and paste it into your program. #include <stdio.h> int main() { printf( "I am alive! Beware.n" ); getchar(); return 0; } The #include is a "preprocessor" directive that tells the compiler to put code from the header called stdio.h into our program before actually creating the executable. By including header files, you can gain access to many different functions--both the printf and getchar functions are included in stdio.h. The next important line is int main(). This line tells the compiler that there is a function named main, and that the function returns an integer, hence int. The "curly braces" ({ and }) signal the beginning and end of functions and other code blocks. The printf function is the standard C way of displaying output on the screen. The quotes tell the compiler that you want to output the literal string as-is (almost). The 'n' sequence is actually treated as a single character that stands for a newline (we'll talk about this later in more detail); for the time being, just remember that there are a few sequences that, when they appear in a string literal, are actually not displayed literally by printf and that 'n' is one of them. The actual effect of 'n' is to move the cursor on your screen to the next line. Notice the semicolon: it tells the compiler that you're at the end of a command, such as a function call. You will see that the semicolon is used to end many lines in C. The next command is getchar(). This is another function call: it reads in a single character and waits for the user to hit enter before reading the character. This line is included because many compiler environments will open a new console window, run the program, and then close the window before you can see the output. This command keeps that window from closing because the program is not done yet because it waits for you to hit enter. Including that line gives you time to see the program run. Finally, at the end of the program, we return a value from main to the operating system by using the return statement. This return value is important as it can be used to tell the operating system whether our program succeeded or not. A return value of 0 means success. The final brace closes off the function. if you save the code into a file, save it as a .c file, and then compile it. If you are using a command-line compiler, such as Borland C++ 5.5, you should read the compiler instructions for information on how to compile.
  • 25. 25 Explaining your Code Comments are critical for all but the most trivial programs and this tutorial will often use them to explain sections of code. When you tell the compiler a section of text is a comment, it will ignore it when running the code, allowing you to use any text you want to describe the real code. To create a comment in C, you surround the text with /* and then */ to block off everything between as a comment. Certain compiler environments or text editorswill change the color of a commented area to make it easier to spot, but some will not. Be certain not to accidentally comment out code (that is, to tell the compiler part of your code is a comment) you need for the program. When you are learning to program, it is also useful to comment out sections of code in order to see how the output is affected. Using Variables It is also possible for your program to accept input. But first, before you try to receive input, you must have a place to store that input. In programming, input and data are stored in variables. There are several different types of variables; when you tell the compiler you are declaring a variable, you must include the data type along with the name of the variable. Several basic types include char, int, and float. Each type can store different types of data. A variable of type char stores a single character, variables of type int store integers (numbers without decimal places), and variables of type float store numbers with decimal places. Each of these variable types - char, int, and float - is each a keyword that you use when you declare a variable. Some variables also use more of the computer's memory to store their values. It may seem strange to have multiple variable types when it seems like some variable types are redundant. But using the right variable size can be important for making your program efficient because some variables require more memory than others. Before you can use a variable, you must tell the compiler about it by declaring it and telling the compiler about what its "type" is. To declare a variable you use the syntax <variable type> <name of variable>;. (The brackets here indicate that your replace the expression with text described within the brackets.) For instance, a basic variable declaration might look like this: int myVariable; It is permissible to declare multiple variables of the same type on the same line; each one should be separated by a comma. If you attempt to use an undefined variable, your program will not run, and you will receive an error message informing you that you have made a mistake. Here are some variable declaration examples: int x;
  • 26. 26 int a, b, c, d; char letter; float the_float; While you can have multiple variables of the same type, you cannot have multiple variables with the same name. Moreover, you cannot have variables and functions with the same name. A final restriction on variables is that variable declarations must come before other types of statements in the given "code block" (a code block is just a segment of code surrounded by { and }). So in C you must declare all of your variables before you do anything else: Wrong #include <stdio.h> int main() { /* wrong! The variable declaration must appear first */ printf( "Declare x next" ); int x; return 0; } Fixed #include <stdio.h> int main() { int x; printf( "Declare x first" ); return 0; } Reading input We'll be using the scanf function to read in a value and then printf to read it back out. Example: #include <stdio.h> int main() { int this_is_a_number; printf( "Please enter a number: " ); scanf( "%d", &this_is_a_number ); printf( "You entered %d", this_is_a_number ); getchar();
  • 27. 27 return 0; } The io in stdio.h stands for "input/output"; std just stands for "standard.") The keyword int declares this_is_a_number to be an integer. The scanf function works by taking a string and some variables modified with &. The string tells scanf what variables to look for: notice that we have a string containing only "%d" -- this tells the scanf function to read in an integer. The second argument of scanf is the variable, sort of. We'll learn more about what is going on later, but the gist of it is that scanf needs to know where the variable is stored in order to change its value. Using & in front of a variable allows you to get its location and give that to scanf instead of the value of the variable. The & gives the scanf function directions to the variable. When the program runs, each call to scanf checks its own input string to see what kinds of input to expect, and then stores the value input into the variable. The second printf statement also contains the same '%d'--both scanf and printf use the same format for indicating values embedded in strings. In this case, printf takes the first argument after the string, the variable this_is_a_number, and treats it as though it were of the type specified by the "format specifier". In this case, printf treats this_is_a_number as an integer based on the format specifier. So what does it mean to treat a number as an integer? If the user attempts to type in a decimal number, it will be truncated (that is, the decimal component of the number will be ignored) when stored in the variable. C Operators Of course, no matter what type you use, variables are uninteresting without the ability to modify them. Several operators used with variables include the following: *, -, +, /, =, ==, >, <. The * multiplies, the / divides, the - subtracts, and the + adds. It is of course important to realize that to modify the value of a variable inside the program it is rather important to use the equal sign. In some languages, the equal sign compares the value of the left and right values, but in C == is used for that task. The equal sign is still extremely useful. It sets the value of the variable on the left side of the equals sign equal to the value on the right side of the equals sign. The operators that perform mathematical functions should be used on the right side of an equal sign in order to assign the result to a variable on the left side. Here are a few examples: a = 4 * 6; /* (Note use of comments and of semicolon) a is 24 */ a = a + 5; /* a equals the original value of a with five added to it */ a == 5 /* Does NOT assign five to a. Rather, it checks to see if a equals 5.*/
  • 28. 28 The other form of equal, ==, is not a way to assign a value to a variable. Rather, it checks to see if the variables are equal. It is extremely useful in many areas of C; for example, you will often use == in such constructions as conditional statements and loops. You can probably guess how < and > function. They are greater than and less than operators. For example: a < 5 /* Checks to see if a is less than five */ a > 5 /* Checks to see if a is greater than five */ a == 5 /* Checks to see if a equals five, for good measure */ let us examine the meaning of TRUE and FALSE in computer terminology. A true statement is one that evaluates to a nonzero number. A false statement evaluates to zero. When you perform comparison with the relational operators, the operator will return 1 if the comparison is true, or 0 if the comparison is false. For example, the check 0 == 2 evaluates to 0. The check 2 == 2 evaluates to a 1. Here are the relational operators, as they are known, along with examples: > greater than 5 > 4 is TRUE < less than 4 < 5 is TRUE >= greater than or equal 4 >= 4 is TRUE <= less than or equal 3 <= 4 is TRUE == equal to 5 == 5 is TRUE != not equal to 5 != 4 is TRUE Conditional Statements in C The ability to control the flow of your program, letting it make decisions on what code to execute, is valuable to the programmer. 1) If The if statement allows you to control if a program enters a section of code or not based on whether a given condition is true or false. One of the important functions of the if statement is that it allows the program to select an action based upon the user's input. For example, by using an if statement to check a user-entered password, your program can decide whether a user is allowed access to the program. Without a conditional statement such as the if statement, programs would run almost the exact same way every time, always following the same sequence of function calls. If statements allow the flow of the program to be changed, which leads to more interesting code. Basic If Syntax The structure of an if statement is as follows:
  • 29. 29 if ( statement is TRUE ) Execute this line of code Here is a simple example that shows the syntax: if ( 5 < 10 ) printf( "Five is now less than ten, that's a big surprise" ); Here, we're just evaluating the statement, "is five less than ten", to see if it is true or not; with any luck, it is! If you want, you can write your own full program including stdio.h and put this in the main function and run it to test. To have more than one statement execute after an if statement that evaluates to true, use braces, like we did with the body of the main function. Anything inside braces is called a compound statement, or a block. When using if statements, the code that depends on the if statement is called the "body" of the if statement. For example: if ( TRUE ) { /* between the braces is the body of the if statement */ Execute all statements inside the body } 2) Else Sometimes when the condition in an if statement evaluates to false, it would be nice to execute some code instead of the code executed when the statement evaluates to true. The "else" statement effectively says that whatever code after it (whether a single line or code between brackets) is executed if the if statement is FALSE. It can look like this: if ( TRUE ) { /* Execute these statements if TRUE */ } else { /* Execute these statements if FALSE */ } 3) Else if Another use of else is when there are multiple conditional statements that may all evaluate to true, yet you want only one if statement's body to execute. You can use an "else if" statement following an if statement and its body; that way, if the first statement is true, the "else if" will be ignored, but if the if statement is false, it will then check the condition for the else if statement. If the if statement
  • 30. 30 was true the else statement will not be checked. It is possible to use numerous else if statements to ensure that only one block of code is executed.example: #include <stdio.h> int main() /* Most important part of the program! */ { int age; /* Need a variable... */ printf( "Please enter your age" ); /* Asks for age */ scanf( "%d", &age ); /* The input is put in age */ if ( age < 100 ) { /* If the age is less than 100 */ printf ("You are pretty young!n" ); /* Just to show you it works... */ } else if ( age == 100 ) { /* I use else just to show an example */ printf( "You are oldn" ); } else { printf( "You are really oldn" ); /* Executed if no other statement is */ } return 0; } Loops Loops are used to repeat a block of code. Being able to have your program repeatedly execute a block of code is one of the most basic but useful tasks in programming -- many programs or websites that produce extremely complex output (such as a message board) are really only executing a single task many times.a loop lets you write a very simple statement to produce a significantly greater result simply by repetition. 1 ) For for ( variable initialization; condition; variable update ) { Code to execute while the condition is true } The variable initialization allows you to either declare a variable and give it a value or give a value to an already existing variable. Second, the condition tells the program that while the conditional expression is true the loop should continue to repeat itself. The variable update section is the easiest way for a for loop to handle changing of the variable. It is possible to do things like x++, x = x + 10, or even x = random ( 5 ), and if you really wanted to, you could call other functions that do nothing to the variable but still have a useful effect on the code. A semicolon separates each of these sections, that is important. Also note that every single one of the sections may be empty, though the semicolons still have to be there. If the condition is empty, it is evaluated as true and the loop will repeat until something else stops it. Example:
  • 31. 31 #include <stdio.h> int main() { int x; /* The loop goes while x < 10, and x increases by one every loop*/ for ( x = 0; x < 10; x++ ) { /* Keep in mind that the loop condition checks the conditional statement before it loops again. consequently, when x equals 10 the loop breaks. x is updated before the condition is checked. */ printf( "%dn", x ); } getchar(); This program is a very simple example of a for loop. x is set to zero, while x is less than 10 it calls printf to display the value of the variable x, and it adds 1 to x until the condition is met. The variable is incremented after the code in the loop is run for the first time. 2) While While loops are very simple. The basic structure is while ( condition ) { Code to execute while the condition is true } The true represents a boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). It can be any combination of boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the code while x equals five or while v equals 7. Notice that a while loop is like a stripped-down version of a for loop-- it has no initialization or update section. However, an empty condition is not legal for a while loop as it is with a for loop. Example: #include <stdio.h> int main() { int x = 0; /* Don't forget to declare variables */ while ( x < 10 ) { /* While x is less than 10 */ printf( "%dn", x ); x++; /* Update x so the condition can be met eventually */ } getchar(); } This was another simple example, but it is longer than the above FOR loop. The easiest way to think of the loop is that when it reaches the brace at the end it jumps back up to the beginning of the loop, which checks the condition again and decides whether to repeat the block another time, or stop and move to the next statement after the block.
  • 32. 32 3) Do while do { } while ( condition ); Notice that the condition is tested at the end of the block instead of the beginning, so the block will be executed at least once. If the condition is true, we jump back to the beginning of the block and execute it again. A do..while loop is almost the same as a while loop except that the loop body is guaranteed to execute at least once. A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and then continue to loop while the condition is true". Example: #include <stdio.h> int main() { int x; x = 0; do { /* "Hello, world!" is printed at least one time even though the condition is false */ printf( "Hello, world!n" ); } while ( x != 0 ); getchar(); } Keep in mind that you must include a trailing semi-colon after the while in the above example. A common error is to forget that a do..while loop must be terminated with a semicolon (the other loops should not be terminated with a semicolon, adding to the confusion). Notice that this loop will execute once, because it automatically executes before checking the condition. Break and Continue Two keywords that are very important to looping are break and continue. The break command will exit the most immediately surrounding loop regardless of what the conditions of the loop are. Break is useful if we want to exit a loop under special circumstances. For example: while (true) { take_turn(player1); take_turn(player2); }
  • 33. 33 This will make the game alternate between having player 1 and player 2 take turns. The only problem with this logic is that there's no way to exit the game; the loop will run forever! Let's try something like this instead: while(true) { if (someone_has_won() || someone_wants_to_quit() == TRUE) {break;} take_turn(player1); if (someone_has_won() || someone_wants_to_quit() == TRUE) {break;} take_turn(player2); } This code accomplishes what we want--the primary loop of the game will continue under normal circumstances, but under a special condition (winning or exiting) the flow will stop and our program will do something else. Continue is another keyword that controls the flow of loops. If you are executing a loop and hit a continue statement, the loop will stop its current iteration, update itself (in the case of for loops) and begin to execute again from the top. Functions A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task. A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function. The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions. A function can also be referred as a method or a sub-routine or a procedure, etc. Defining aFunction The general form of a function definition in C programming language is as follows – return_type function_name( parameter list ) { body of the function } A function definition in C programming consists of a function header and a function body. Here are all the parts of a function −
  • 34. 34  Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.  Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.  Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.  Function Body − The function body contains a collection of statements that define what the function does. Example Given below is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum value between the two − /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } Defining aFunction A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.
  • 35. 35 A function declaration has the following parts − return_type function_name( parameter list ); For the above defined function max(), the function declaration is as follows − int max(int num1, int num2); Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration − int max(int, int); Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function. Calling aFunction While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task. When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function- ending closing brace is reached, it returns the program control back to the main program. To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value. For example − #include <stdio.h> /* function declaration */ int max(int num1, int num2); int main () { /* local variable definition */ int a = 100; int b = 200; int ret;
  • 36. 36 /* calling a function to get max value */ ret = max(a, b); printf( "Max value is : %dn", ret ); return 0; } /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } Function Arguments If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
  • 37. 37 S.N. Call Type & Description 1 Call by value This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. 2 Call by reference This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. Switch case in C Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply values that can be expressed as an integer, such as the value of a char). The basic format for using switch case is outlined below. The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point. switch ( <variable> ) { case this-value: Code to execute if <variable> == this-value break; case that-value: Code to execute if <variable> == that-value break; ... default: Code to execute if <variable> does not equal the value following any of the cases break; } The condition of a switch statement is a value. The case says that if it has the value of whatever is after that case then do whatever follows the colon. The break is used to break out of the case statements. Break is a keyword that breaks out of the code block, usually surrounded by braces, which it is in. In this case, break prevents the program from falling through and executing the code in all the other case statements. An important thing to note about the switch statement is that the case values may only be constant integral expressions.
  • 38. 38 Blink Example In Arduino Now after having studied about the hardware as well as the software, A typical program for a beginning Arduino programmer blinks an LED repeatedly. This program uses the functions pinMode, digitalWrite, and delay, which are provided by the internal libraries included in the IDE environment. The program is usually loaded in the Arduino by the manufacturer. Blink Turns on an LED on for one second, then off for one second, repeatedly. Most Arduinos have an on- board LED you can control. On the UNO, MEGA and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to the correct LED pin independent of which board is used. Program Source Code:- // the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second }
  • 39. 39