0% found this document useful (0 votes)
13 views

PG-IOT-U3

This document provides an overview of programming fundamentals using C with Arduino IDE, detailing the installation process, key features of Arduino boards, and the structure of Arduino programs. It covers essential concepts such as data types, variables, constants, and operators, along with step-by-step instructions for setting up the Arduino IDE and uploading programs. The document also explains the roles of various components on the Arduino board and introduces programming structures like setup() and loop() functions.

Uploaded by

Vimal Cheyyar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

PG-IOT-U3

This document provides an overview of programming fundamentals using C with Arduino IDE, detailing the installation process, key features of Arduino boards, and the structure of Arduino programs. It covers essential concepts such as data types, variables, constants, and operators, along with step-by-step instructions for setting up the Arduino IDE and uploading programs. The document also explains the roles of various components on the Arduino board and introduces programming structures like setup() and loop() functions.

Uploaded by

Vimal Cheyyar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

INTERNET OF THINGS

UNIT – 3
Programming Fundamentals with C using Arduino IDE: Installing and setting up the arduino IDE –
basuc stbtax – data types / variables / constant – operators – conditional statement and loops – using
arduino C Library functions for serial, delay and other invoking functions - strings and mathematics
library functions.

Programming Fundamentals with C using Arduino IDE:


Arduino is a prototype platform (open-source) based on an easy-to-use hardware and software. It
consists of a circuit board, which can be programed (referred to as a microcontroller) and a ready-
made software called Arduino IDE (Integrated Development Environment), which is used to write and
upload the computer code to the physical board.
Arduino provides a standard form factor that breaks the functions of the micro-controller into a more
accessible package.

The key features are −


 Arduino boards are able to read analog or digital input signals from different sensors and turn it
into an output such as activating a motor, turning LED on/off, connect to the cloud and many other
actions.
 You can control your board functions by sending a set of instructions to the microcontroller on the
board via Arduino IDE (referred to as uploading software).
 Unlike most previous programmable circuit boards, Arduino does not need an extra piece of
hardware (called a programmer) in order to load a new code onto the board. You can simply use a
USB cable.
 Additionally, the Arduino IDE uses a simplified version of C++, making it easier to learn to
program.
 Finally, Arduino provides a standard form factor that breaks the functions of the micro-controller
into a more accessible package.

What is Arduino?
With the increasing demand for programming, there was a need for a device that could program
electrical devices therefore, Arduino was introduced. Arduino is a board made up of several
interconnected components like microcontrollers, digital pins, analog pins, power supplies, and
crystal oscillators which give Arduino the ability to program electronic instruments. You must be
familiar with the idea that an Arduino board can be programmed to illuminate an LED. The Arduino
has its hardware and software using which it can program devices. Let us take a look at the Arduino
board.
 Microcontroller: The microcontroller used on the Arduino board is essentially used for
controlling all major operations. The microcontroller is used to coordinate the input taken and
execute the code written in a high-level language.
 Analog Reference pin: Analog pins are used for general purposes like supporting 10-bit analog-
to-digital conversion (ADC) which is performed using analog the Read() function. Analog pins
are particularly helpful since they can store 0-255 bits which is not possible using digital pins.
 Digital Pins: Digital pins are used for general purposes like taking input or generating output.
The commands that are used for setting the modes of the pins are pinMode(), digitalRead(), and
digitalWrite() commands.
 Reset Button: The reset button on the Arduino board is used for setting all the components of
Arduino to their default values. In case you want to stop the Arduino in between you can use this
reset button.
 Power and Ground Pins: As the name suggests, power and ground pins are used to supply the
power needed for driving the Arduino board. The ground pins are usually 0V to set a reference
level for the circuit.
 USB (universal serial bus): The Arduino needs certain protocols for communication purposes
and the universal serial bus is used for this purpose. It helps to connect Arduino,
microcontrollers with other raspberry pies.

Installing and setting up the arduino IDE


After learning about the main parts of the Arduino UNO board, we are ready to learn how to set up the
Arduino IDE. Once we learn this, we will be ready to upload our program on the Arduino board.
In this section, we will learn in easy steps, how to set up the Arduino IDE on our computer and
prepare the board to receive the program via USB cable.

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

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

Step 2 − Download Arduino IDE Software.


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

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.

Here, we are selecting just one of the examples with the name Blink. It turns the LED on and off with
some time delay. You can select any other example from the list.
Step 6 − Select your Arduino board.
To avoid any error while uploading your program to the board, you must select the correct Arduino
board name, which matches with the board connected to your computer.
Go to Tools → Board and select your board.

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

Step 7 − Select your serial port.


Select the serial device of the Arduino board. Go to Tools → Serial Port menu. This is likely to be
COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out, you can
disconnect your Arduino board and re-open the menu, the entry that disappears should be of the
Arduino board. Reconnect the board and select that serial port.
Step 8 − Upload the program to your board.
Before explaining how we can upload our program to the board, we must demonstrate the function of
each symbol appearing in the Arduino IDE toolbar.

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


B − Used to upload a program to the Arduino board.
C − Shortcut used to create a new sketch.
D − Used to directly open one of the example sketch.
E − Used to save your sketch.
F − Serial monitor used to receive serial data from the board and send the serial data to the board.
Now, simply click the "Upload" button in the environment. Wait a few seconds; you will see the RX and
TX LEDs on the board, flashing. If the upload is successful, the message "Done uploading" will appear
in the status bar.

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

Arduino - Program Structure


The Arduino program structure and we will learn more new terminologies used in the Arduino world.
The Arduino software is open-source. The source code for the Java environment is released under the
GPL and the C/C++ microcontroller libraries are under the LGPL.
Sketch − The first new terminology is the Arduino program called “sketch”.
Structure
Arduino programs can be divided in three main parts: Structure, Values (variables and constants),
and Functions. In this tutorial, we will learn about the Arduino software program, step by step, and
how we can write the program without any syntax or compilation error.

Let us start with the Structure. Software structure consist of two main functions −
 Setup( ) function
 Loop( ) function

Void setup ( ) {

}
 PURPOSE − The setup() function is called when a sketch starts. Use it to initialize the variables,
pin modes, start using libraries, etc. The setup function will only run once, after each power up or
reset of the Arduino board.
 INPUT − -
 OUTPUT − -
 RETURN − -

Void Loop ( ) {

 PURPOSE − After creating a setup() function, which initializes and sets the initial values,
the loop() function does precisely what its name suggests, and loops consecutively, allowing your
program to change and respond. Use it to actively control the Arduino board.
 INPUT − -
 OUTPUT − -
 RETURN − -

Arduino - Data Types


Data types in C refers to an extensive system used for declaring variables or functions of different
types. The type of a variable determines how much space it occupies in the storage and how the bit
pattern stored is interpreted.

The following table provides all the data types that you will use during Arduino programming.
void Boolean char Unsigned char byte int Unsigned int word

long Unsigned long short float double array String-char array String-object

void
The void keyword is used only in function declarations. It indicates that the function is expected to
return no information to the function from which it was called.
Example
Void Loop ( ) {
// rest of the code
}
Boolean
A Boolean holds one of two values, true or false. Each Boolean variable occupies one byte of memory.
Example
boolean val = false ; // declaration of variable with type boolean and initialize it with false
boolean state = true ; // declaration of variable with type boolean and initialize it with true
Char
A data type that takes up one byte of memory that stores a character value. Character literals are
written in single quotes like this: 'A' and for multiple characters, strings use double quotes: "ABC".
However, characters are stored as numbers. You can see the specific encoding in the ASCII chart. This
means that it is possible to do arithmetic operations on characters, in which the ASCII value of the
character is used. For example, 'A' + 1 has the value 66, since the ASCII value of the capital letter A is
65.
Example
Char chr_a = ‘a’ ;//declaration of variable with type char and initialize it with character a
Char chr_c = 97 ;//declaration of variable with type char and initialize it with character 97

Unsigned char
Unsigned char is an unsigned data type that occupies one byte of memory. The unsigned char data
type encodes numbers from 0 to 255.
Example
Unsigned Char chr_y = 121 ; // declaration of variable with type Unsigned char and initialize it with
character y
byte
A byte stores an 8-bit unsigned number, from 0 to 255.
Example
byte m = 25 ;//declaration of variable with type byte and initialize it with 25
int
Integers are the primary data-type for number storage. int stores a 16-bit (2-byte) value. This yields a
range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1).

The int size varies from board to board. On the Arduino Due, for example, an int stores a 32-bit (4-
byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a
maximum value of (2^31) - 1).
Example
int counter = 32 ;// declaration of variable with type int and initialize it with 32
Unsigned int
Unsigned ints (unsigned integers) are the same as int in the way that they store a 2 byte value. Instead
of storing negative numbers, however, they only store positive values, yielding a useful range of 0 to
65,535 (2^16) - 1). The Due stores a 4 byte (32-bit) value, ranging from 0 to 4,294,967,295 (2^32 - 1).
Example
Unsigned int counter = 60 ; // declaration of variable with
type unsigned int and initialize it with 60
Word
On the Uno and other ATMEGA based boards, a word stores a 16-bit unsigned number. On the Due
and Zero, it stores a 32-bit unsigned number.
Example
word w = 1000 ;//declaration of variable with type word and initialize it with 1000
Long
Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from -
2,147,483,648 to 2,147,483,647.
Example
Long velocity = 102346 ;//declaration of variable with type Long and initialize it with 102346
Unsigned long
Unsigned long variables are extended size variables for number storage and store 32 bits (4 bytes).
Unlike standard longs, unsigned longs will not store negative numbers, making their range from 0 to
4,294,967,295 (2^32 - 1).
Example
Unsigned Long velocity = 101006 ;// declaration of variable with
type Unsigned Long and initialize it with 101006
short
A short is a 16-bit data-type. On all Arduinos (ATMega and ARM based), a short stores a 16-bit (2-
byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value
of (2^15) - 1).
Example
short val = 13 ;//declaration of variable with type short and initialize it with 13
float
Data type for floating-point number is a number that has a decimal point. Floating-point numbers are
often used to approximate the analog and continuous values because they have greater resolution
than integers.
Floating-point numbers can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They are
stored as 32 bits (4 bytes) of information.
Example
float num = 1.352;//declaration of variable with type float and initialize it with 1.352
double
On the Uno and other ATMEGA based boards, Double precision floating-point number occupies four
bytes. That is, the double implementation is exactly the same as the float, with no gain in precision. On
the Arduino Due, doubles have 8-byte (64 bit) precision.
Example
double num = 45.352 ;// declaration of variable with type double and initialize it with 45.352

Arduino - Variables & Constants


Before we start explaining the variable types, a very important subject we need to make sure, you fully
understand is called the variable scope.
What is Variable Scope?
Variables in C programming language, which Arduino uses, have a property called scope. A scope is a
region of the program and there are three places where variables can be declared. They are −
 Inside a function or a block, which is called local variables.
 In the definition of function parameters, which is called formal parameters.
 Outside of all functions, which is called global variables.

Local Variables
Variables that are declared inside a function or block are local variables. They can be used only by the
statements that are inside that function or block of code. Local variables are not known to function
outside their own.

Following is the example using local variables −


Void setup () {
}
Void loop () {
int x , y ;
int z ; Local variable declaration
x = 0;
y = 0; actual initialization
z = 10;
}

Global Variables
Global variables are defined outside of all the functions, usually at the top of the program. The global
variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration.

The following example uses global and local variables −


Int T , S ;
float c = 0 ; Global variable declaration

Void setup () {

Void loop () {
int x , y ;
int z ; Local variable declaration
x = 0;
y = 0; actual initialization
z = 10;
}

Arduino - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C
language is rich in built-in operators and provides the following types of operators −
 Arithmetic Operators
 Comparison Operators
 Boolean Operators
 Bitwise Operators
 Compound Operators

Arithmetic Operators
Assume variable A holds 10 and variable B holds 20 then −
Show Example
Operator
Operator name Description Example
simple

assignment Stores the value to the right of the equal sign in


= A=B
operator the variable to the left of the equal sign.

A + B will
addition + Adds two operands
give 30
A - B will give
subtraction - Subtracts second operand from the first
-10

A * B will give
multiplication * Multiply both operands
200

B / A will
division / Divide numerator by denominator
give 2

Modulus Operator and remainder of after an B % A will


modulo %
integer division give 0

Comparison Operators
Assume variable A holds 10 and variable B holds 20 then −
Show Example
Operator Operator
Description Example
name simple

Checks if the value of two operands is equal or not, if (A == B) is


equal to ==
yes then condition becomes true. not true

Checks if the value of two operands is equal or not, if (A != B) is


not equal to !=
values are not equal then condition becomes true. true

Checks if the value of left operand is less than the


(A < B) is
less than < value of right operand, if yes then condition becomes
true
true.

Checks if the value of left operand is greater than the


(A > B) is
greater than > value of right operand, if yes then condition becomes
not true
true.

Checks if the value of left operand is less than or equal


less than or (A <= B) is
<= to the value of right operand, if yes then condition
equal to true
becomes true.

Checks if the value of left operand is greater than or


greater than or (A >= B) is
>= equal to the value of right operand, if yes then
equal to not true
condition becomes true.

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to
boost your career.

Boolean Operators
Assume variable A holds 10 and variable B holds 20 then −
Show Example
Operator Operator
Description Example
name simple
Called Logical AND operator. If both the operands are non- (A && B) is
and &&
zero then then condition becomes true. true

Called Logical OR Operator. If any of the two operands is (A || B) is


or ||
non-zero then then condition becomes true. true

Called Logical NOT Operator. Use to reverses the logical


!(A && B) is
not ! state of its operand. If a condition is true then Logical NOT
false
operator will make false.

Bitwise Operators
Assume variable A holds 60 and variable B holds 13 then −
Show Example
Operator Operator
Description Example
name simple

Binary AND Operator copies a bit to the result if it (A & B) will give 12
and &
exists in both operands. which is 0000 1100

Binary OR Operator copies a bit if it exists in either (A | B) will give 61


or |
operand which is 0011 1101

Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49


xor ^
one operand but not both. which is 0011 0001

Binary Ones Complement Operator is unary and (~A ) will give -60
not ~
has the effect of 'flipping' bits. which is 1100 0011

Binary Left Shift Operator. The left operands value


A << 2 will give 240
shift left << is moved left by the number of bits specified by
which is 1111 0000
the right operand.

Binary Right Shift Operator. The left operands


A >> 2 will give 15
shift right >> value is moved right by the number of bits
which is 0000 1111
specified by the right operand.

Compound Operators
Assume variable A holds 10 and variable B holds 20 then −
Show Example
Operator
Operator name Description Example
simple

Increment operator, increases integer value by


increment ++ A++ will give 11
one

Decrement operator, decreases integer value


decrement -- A-- will give 9
by one

compound += Add AND assignment operator. It adds right B += A is


addition operand to the left operand and assign the equivalent to B =
result to left operand B+ A

Subtract AND assignment operator. It subtracts B -= A is


compound
-= right operand from the left operand and assign equivalent to B =
subtraction
the result to left operand B-A

Multiply AND assignment operator. It B*= A is


compound
*= multiplies right operand with the left operand equivalent to B =
multiplication
and assign the result to left operand B* A

Divide AND assignment operator. It divides left B /= A is


compound
/= operand with the right operand and assign the equivalent to B =
division
result to left operand B/A

Modulus AND assignment operator. It takes B %= A is


compound
%= modulus using two operands and assign the equivalent to B =
modulo
result to left operand B%A

compound A |= 2 is same as
|= bitwise inclusive OR and assignment operator
bitwise or A=A|2

compound A &= 2 is same as


&= Bitwise AND assignment operator
bitwise and A=A&2

Arduino - Control Statements


Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program. It should be along with a statement or statements to be executed
if the condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.

Following is the general form of a typical decision making structure found in most of the programming
languages −
S.NO
Loop & Description
.

while loop
1 while loops will loop continuously, and infinitely, until the expression inside the parenthesis, ()
becomes false. Something must change the tested variable, or the while loop will never exit.

do…while loop
2 The do…while loop is similar to the while loop. In the while loop, the loop-continuation
condition is tested at the beginning of the loop before performed the body of the loop.

for loop
3 A for loop executes statements a predetermined number of times. The control expression for
the loop is initialized, tested and manipulated entirely within the for loop parentheses.

Nested Loop
4 C language allows you to use one loop inside another loop. The following example illustrates
the concept.

Infinite loop
It is the loop having no terminating condition, so the loop becomes infinite.

Using arduino C Library functions for serial, delay and other invoking
functions

Arduino - Math Library


The Arduino Math library (math.h) includes a number of useful mathematical functions for
manipulating floating-point numbers.
Library Macros
Following are the macros defined in the header math.h −
Given below is the list of macros defined in the header math.h

Library Functions
The following functions are defined in the header math.h −
Given below is the list of functions are defined in the header math.h
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified
expert to boost your career.

Example
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 : ");
Control Statements
Control Statements are elements in Source Code that control the flow of program execution. They are

S.NO
Control Statement & Description
.

If statement
It takes an expression in parenthesis and a statement or block of statements. If the expression
1
is true then the statement or block of statements gets executed otherwise these statements are
skipped.

If …else statement
2 An if statement can be followed by an optional else statement, which executes when the
expression is false.

If…else if …else statement


3 The if statement can be followed by an optional else if...else statement, which is very useful to
test various conditions using single if...else if statement.

switch case statement


4 Similar to the if statements, switch...case controls the flow of programs by allowing the
programmers to specify different codes that should be executed in various conditions.

Conditional Operator ? :
5
The conditional operator ? : is the only ternary operator in C.

Arduino - Loops
Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages –

C programming language provides the following types of loops to handle looping requirements.

You might also like