[go: up one dir, main page]

0% found this document useful (0 votes)
32 views20 pages

PG Iot Unit 3

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

PG Iot Unit 3

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

UNIT-3

Arduino
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 hardware to upload
programs and communicate with them.

Download Arduino IDE Software.

Arduino IDE from the Download page on the Arduino Official


website(www.arduino.cc/en/software). You must select your software, which is compatible
with your operating system (Windows, IOS, or Linux). After your file download is complete,
unzip the file.

Step 3 − Power up your board.

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

Step 4 − Launch Arduino IDE.

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

Step 5 − Open your first project.

Once the software starts, you have two options −

 Create a new project.


 Open an existing project example.

To create a new project, select File → New.


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

Sketches
Programs
written using Arduino
Software (IDE) are
called sk etches. 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.

NB: Versions of the Arduino Software (IDE) prior to 1.0 saved sketches with the
extension .pde. It is possible to open these files with version 1.0, you will be prompted to save
the sketch with the .ino extension on save.

Verify button.

Verify Checks your code for errors compiling it.

Upload button.

Upload Compiles your code and uploads it to the configured board.

Note: If you are using an external programmer with your board, you can hold down the "shift"
key on your computer when using this icon. The text will change to "Upload using
Programmer"
New file.

New Creates a new sketch.

Open file.

Open Presents a menu of all the sketches in your sketchbook. Clicking one will open it within
the current window overwriting its content.

Save file.

Save Saves your sketch.

Serial Monitor button.

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.

File
 New Creates a new instance of the editor, with the bare minimum structure of a sketch
already in place.
 Open Allows to load a sketch file browsing through the computer drives and folders.
 Open Recent Provides a short list of the most recent sketches, ready to be opened.
 Sketchbook Shows the current sketches within the sketchbook folder structure; clicking
on any name opens the corresponding sketch in a new editor instance.
 Examples Any example provided by the Arduino Software (IDE) or library shows up in
this menu item. All the examples are structured in a tree that allows easy access by
topic or library.
 Close Closes the instance of the Arduino Software from which it is clicked.
 Save Saves the sketch with the current name. If the file hasn't been named before, a
name will be provided in a "Save as.." window.
 Save as... Allows to save the current sketch with a different name.
 Page Setup It shows the Page Setup window for printing.
 Print Sends the current sketch to the printer according to the settings defined in Page
Setup.
 Preferences Opens the Preferences window where some settings of the IDE may be
customized, as the language of the IDE interface.
 Quit Closes all IDE windows. The same sketches open when Quit was chosen will be
automatically reopened the next time you start the IDE.

Edit
 Undo/Redo Goes back of one or more steps you did while editing; when you go back,
you may go forward with Redo.
 Cut Removes the selected text from the editor and places it into the clipboard.
 Copy Duplicates the selected text in the editor and places it into the clipboard.
 Copy for Forum Copies the code of your sketch to the clipboard in a form suitable for
posting to the forum, complete with syntax coloring.
 Copy as HTML Copies the code of your sketch to the clipboard as HTML, suitable for
embedding in web pages.
 Paste Puts the contents of the clipboard at the cursor position, in the editor.
 Select All Selects and highlights the whole content of the editor.
 Comment/Uncomment Puts or removes the // comment marker at the beginning of
each selected line.
 Increase/Decrease Indent Adds or subtracts a space at the beginning of each selected
line, moving the text one space on the right or eliminating a space at the beginning.
 Find Opens the Find and Replace window where you can specify text to search inside
the current sketch according to several options.
 Find Next Highlights the next occurrence - if any - of the string specified as the search
item in the Find window, relative to the cursor position.
 Find Previous Highlights the previous occurrence - if any - of the string specified as the
search item in the Find window relative to the cursor position.

Sketch
 Verify/Compile Checks your sketch for errors compiling it; it will report memory usage
for code and variables in the console area.
 Upload Compiles and loads the binary file onto the configured board through the
configured Port.
 Upload Using Programmer This will overwrite the bootloader on the board; you will
need to use Tools > Burn Bootloader to restore it and be able to Upload to USB serial
port again. However, it allows you to use the full capacity of the Flash memory for your
sketch. Please note that this command will NOT burn the fuses. To do so a Tools -> Burn
Bootloader command must be executed.
 Export Compiled Binary Saves a .hex file that may be kept as archive or sent to the
board using other tools.
 Show Sketch Folder Opens the current sketch folder.
 Include Library Adds a library to your sketch by inserting #include statements at the
start of your code. For more details, see libraries below. Additionally, from this menu
item you can access the Library Manager and import new libraries from .zip files.
 Add File... Adds a supplemental file to the sketch (it will be copied from its current
location). The file is saved to the data subfolder of the sketch, which is intended for
assets such as documentation. The contents of the data folder are not compiled, so they
do not become part of the sketch program.

Tools
 Auto Format This formats your code nicely: i.e. indents it so that opening and closing
curly braces line up, and that the statements inside curly braces are indented more.
 Archive Sketch Archives a copy of the current sketch in .zip format. The archive is
placed in the same directory as the sketch.
 Fix Encoding & Reload Fixes possible discrepancies between the editor char map
encoding and other operating systems char maps.
 Serial Monitor Opens the serial monitor window and initiates the exchange of data
with any connected board on the currently selected Port. This usually resets the board,
if the board supports Reset over serial port opening.
 Board Select the board that you're using.
 Port This menu contains all the serial devices (real or virtual) on your machine. It
should automatically refresh every time you open the top-level tools menu.
 Programmer For selecting a hardware programmer when programming a board or
chip and not using the onboard USB-serial connection.

Help
Here you find easy access to a number of documents that come with the Arduino Software
(IDE). You have access to Getting Started, Reference, this guide to the IDE and other
documents locally, without an internet connection. The documents are a local copy of the
online ones and may link back to our online website.

 Find in Reference This is the only interactive function of the Help menu: it directly selects
the relevant page in the local copy of the Reference for the function or command under
the cursor.

Sketchbook
The Arduino Software (IDE) uses the concept of a sketchbook: a standard place to store your
programs (or sketches). The sketches in your sketchbook can be opened from the File >
Sketchbook menu or from the Open button on the toolbar. The first time you run the Arduino
software, it will automatically create a directory for your sketchbook. You can view or change
the location of the sketchbook location from with the Preferences dialog.

Beginning with version 1.0, files are saved with a .ino file extension. Previous versions
use the .pde extension. You may still open .pde named files in version 1.0 and later, the
software will automatically rename the extension to .ino.

Some libraries are included with the Arduino software. Others can be downloaded from a
variety of sources or through the Library Manager. Starting with version 1.0.5 of the IDE, you
do can import a library from a zip file and use it in an open sketch.

Arduino Programming
The Arduino programming language is based on C/C++, but it is designed to be simpler and
easier to learn. The most intuitive way to think about programming is like building with LEGO
blocks: certain rules must be followed and different building blocks can be used to build bigger
parts.

General Syntax

 Every line must either end with a semicolon ‘;’ unless it’s a conditional, loop, or function
 Conditionals, loops, and functions are enclosed in curly braces {}
 Comments start with a //
o Comments are text that the program ignores
o Used to label and explain code
Datatypes
Datatypes are the different kinds of data values that can be used, manipulated and stored using
C++. The table below includes the most basic and widely used datatypes.

Dataty What it stores Default


Notes
pe (examples) value

A true value (1, TRUE,


Boolea HIGH) or 0, FALSE, English boolean values such as
n a false value (0, FALSE, LOW TRUE or LOW must be in all caps
LOW)

An integer number (-5,


int 0 Can be positive or negative
15, 1047, etc.)

A decimal number (-0.5,


double 0 Can be positive or negative
123.77, etc.)

A decimal number (-0.5,


float 0 Can be positive or negative
123.77, etc.)

A single character (‘c’, Indetermina


char Must be enclosed in single quotes
‘A’, ‘5’, ‘?’, etc.) te

A sequence of
characters (“Hello
string Empty (“”) Must be enclosed in double quotes
World!”,
“10”, “157+5”, etc.)

Operators
Operators perform operations on variables and constants. The results of these
operations are usually stored in a variable. The table below includes common
operators.
Operat
What it does Notes
or

= Assigns a value to a variable

+ Adds two or more values

- Subtracts two or more values

* Multiplies two or more values

/ Divides two or more values

Usually used in
++ Increment by 1
loops

Usually used in
-- Decrement by 1
loops

Usually used in
== Checks if two value are equal
conditionals

Usually used in
!= Checks if two value are not equal
conditionals

Usually used in
> or < Less than/Greater than comparison
conditionals

<= or Usually used in


Less than/greater than or equal to comparison
>= conditionals

Boolean AND or Boolean OR Used to cascade multiple Usually used in


&& or ||
Boolean operations conditionals
Constants and Variables
Constants and variables hold data according to their datatype. They need to be given a
name so that they can be referred to later. Constants hold data that will NOT change while a
program is running. Constants usually contain pin numbers or sensor threshold values.
Variables contain data that WILL change while a program is running. Variables usually contain
sensor values and other values that need to have mathematical operations done on them. Below
is an example of how to create different
constants and variables.

Constants & Variables

Conditional Statements
Conditional statements run code enclosed by their curly brackets when a condition is met.

Conditional statements

Loops
Loops run the code enclosed by their curly brackets a specific amount of times or until a
condition is met. While-loop While-loops are used to perform a task until a condition is met For-
loop For-loops are used when you want something to run a specific number of times. Although
they seem complicated at first, the structure of most for-loops is the same. In the parentheses,
the first part sets a variable (usually ‘i’ for ‘index’) to a value used to begin a count, the middle is
the condition when the loop stops, and the third part is where you increment or decrement the
counting variable.
While and for-loops

Functions
Functions are predefined sections of code that can be called multiple times to perform a defined
task. These are typically used when a programmer needs to perform the same task multiple
times. Figure 4 shows the anatomy of a function.

Function Prototype

The header portion is the function declaration. This tells the code what the function will return
(return type), what the name of the function is (function name), and any parameters needed.The
return type can be any valid Arduino C data type. If the function will not return any values, the
return type should be void. Parameters are optional when creating a function.
For example, the following function is called addOne. This function takes in an integer, and
returns that integer value plus one.

addOne() Function
An example use of this function is below. After calling the function addOne(4), the value of the
integer number would be 5.

Using the addOne() function

Commonly Used Arduino Functions


These functions are included with Arduino C to be used with the Arduino board.

Function What it does

pinMode(pin,mode) Sets a pin as an input or output

digitalWrite(pin, value) Sets a digital output pin to HIGH or LOW

digitalRead(pin) Reads a digital input pin as HIGH or LOW

analogWrite(pin, value) Sets an analog output pin to a value 0-1023

analogRead(pin) Reads an analog output pin as a value 0-1023

delay(milliseconds) Pauses the program for a certain amount of time

Serial.begin(value) Begins the Serial Monitor with a baud rate of value

Serial.print(value) Prints the value (variable) to the Serial Monitor.


Arduino Libraries
Arduino Libraries are commonly used for robot movement and can be helpful with
various sensors. Libraries are files that are already written in order to provide your sketch with
extra functionality through various functions.
To use an existing library in a sketch simply go to the Sketch menu, choose "Import Library", and
pick from the libraries available. This will insert an #include statement at the top of the sketch
for each header (.h) file in the library's folder. These statements make the public functions and
constants defined by the library available to your sketch. They also signal the Arduino
environment to link that library's code with your sketch when it is compiled or uploaded.
To install a third party library download the libraries zip file to the Arduino folder of your
computer. Extract the library to its own folder. Arduino must be restarted in order to use the
library.

Standard Libraries

The standard libraries are listed below:

EEPROM

It stands for Electronic Erasable Programmable Read Only Memory. The EEPROM is
associated with the microcontroller present on the AVR or Arduino Boards. The EEPROM library
allows us to read the bytes stored in the memory when the power of the board is off.

#include <EEPROM.h>

Ethernet Library

The Ethernet library works with the Arduino Ethernet shield and other related devices. The
Ethernet library allows us to connect the Arduino board to the Internet.

The SPI bus acts as an intermediate between the board and the shield.

#include <Ethernet.h>
#include <SPI.h>
Firmata Library

It is used to implement the firmware protocol, which communicates with the software on
the host computer.

include <Firmata.h>

GSM Library

The GSM library allows us to perform the operations on the Arduino board similar to the GSM
phone, such as internet connection, send and receive messages, and to place voice calls.
#include <GSM.h>
SPI Library

The SPI (Serial Peripheral Interface) is a serial data protocol. The microcontrollers use the
serial protocol to communicate over short distances with one or more peripheral devices
quickly.The required connection of SPI is a full-duplex that allows devices to simultaneously sent
and receive data.

include <SPI.h>
Software Serial Library

The Software Serial Library permits serial communication over digital Input/output pins. The 0
and 1 pins are inbuilt on Arduino for the serial interface. We can include multiple serial ports in
our code that can operate with speed upto 115200 bps (bits per second).

#include <SoftwareSerial.h>

WiFi Library

The WiFi library permits Arduino to establish a connection with the internet. It can either be a
server to receive the incoming connections or a client to perform outgoing connections.

#include <WiFi.h>
Install a library in Arduino?
o open the library manager to install a new library in Arduino. Click on Sketch ->
Include Library -> Manage Libraries, as shown below:
o A dialog box containing various libraries will appear, as shown below:

o A list of libraries will appear that are ready to install. We need to select the specific
library -> select the version -> click on Install button, as shown below:
Math and character functions in Arduino

The list of math functions that Arduino gives us.

1. abs()
2. constrain()
3. map()
4. max()
5. min()
6. sq()
7. sqrt()
8. pow()

Arduino String

The string is a data type that stores text rather than the integer values. It is similar to other data
types such as integer, float, etc., in Arduino.
The string is an array of characters or a set of characters that consists of numbers,
spaces, and special characters from the ASCII table.

Serial.print()

const int length = 20;


1. char myString[length] = "Hello Arduino";
2. // we can also specify as char myString[20] = "Hello Arduino";
3. void setup()
4. {
5. Serial.begin(9600);
6. }
7. void loop()
8. {
9. for( int i=0; i<length; i = i+1)
10. {
11. if(myString[i]== '\0')
12. // it will stop printing when it sees a null character
13. {
14. break; //
15. }
16. Serial.print(myString[i]);
17. }
18. Serial.println();
19. delay(500);
20. }

The code will print Hello Arduino multiple times, as shown below:

Serial.println() with string

In the case of println() function, we need not require any for loop or condition to print.

1. const int length = 15;


2. char myString[length] = "Hello Arduino";
3. void setup()
4. {
5. Serial.begin(9600);
6. }
7. void loop()
8. {
9. Serial.println(myString);
10. delay(500);
11. }

The following example shows how to use the most common math.h library functions −

double double__x = 45.45 ;


double double__y = 30.20 ;

void setup() {
Serial.begin(9600);
Serial.print("cos num = ");
Serial.println (cos (double__x) ); // returns cosine of x
Serial.print("absolute value of num = ");
Serial.println (fabs (double__x) ); // absolute value of a float
Serial.print("floating point modulo = ");
Serial.println (fmod (double__x, double__y)); // floating point modulo
Serial.print("sine of num = ");
Serial.println (sin (double__x) ) ;// returns sine of x
Serial.print("square root of num : ");
Serial.println ( sqrt (double__x) );// returns square root of x
Serial.print("tangent of num : ");
Serial.println ( tan (double__x) ); // returns tangent of x
Serial.print("exponential value of num : ");
Serial.println ( exp (double__x) ); // function returns the exponential value of x.
Serial.print("cos num : ");
Serial.println (atan (double__x) ); // arc tangent of x
Serial.print("tangent of num : ");
Serial.println (atan2 (double__y, double__x) );// arc tangent of y/x
Serial.print("arc tangent of num : ");
Serial.println (log (double__x) ) ; // natural logarithm of x
Serial.print("cos num : ");
Serial.println ( log10 (double__x)); // logarithm of x to base 10.
Serial.print("logarithm of num to base 10 : ");
Serial.println (pow (double__x, double__y) );// x to power of y
Serial.print("power of num : ");
Serial.println (square (double__x)); // square of x
}
void loop() {
}

Result
cos num = 0.10
absolute value of num = 45.45
floating point modulo =15.25
sine of num = 0.99
square root of num : 6.74
tangent of num : 9.67
exponential value of num : ovf
cos num : 1.55
tangent of num : 0.59
arc tangent of num : 3.82
cos num : 1.66
logarithm of num to base 10 : inf
power of num : 2065.70

You might also like