O Level m4 r5 Building Iot Applications and C Programming Chapter 4 Download PDF Notes Free
O Level m4 r5 Building Iot Applications and C Programming Chapter 4 Download PDF Notes Free
UPCISS
R5)
Internet of Things and its
Applications
Chapter-4
Building IoT applications
Video Tutorial
O-Level M4-R5 Full
Video Playlist Available
on YouTube Channel
UPCISS
1
Chapter 4- Building IoT applications
Introduction to Arduino Board and IDE
ARDUINO एक open source हार्ड वेयर और सॉफ्टवेयर कम्पनी और कम्युननटी
है, जो र्ेवलपमेंट बोर्ड बनाती है. र्ेवलपमेंट बोर्ड यानन एक
embedded system नजसमे microcontroller या microprocessor होता है. साथ ही
साथ उसमे पॉवर सप्लाई रे गुलेटसड, मेमोरी, communication ports, etc. होता
है.
Microcontroller ATmega328P
Operating Voltage 5V
Input Voltage 7-12V
(recommended)
Input Voltage (limit) 6-20V
Digital I/O Pins 14 (of which 6 provide PWM output)
PWM Digital I/O Pins 6
Analog Input Pins 6
DC Current per I/O Pin 20 Ma
DC Current for 3.3V Pin 50 Ma
2
Flash Memory 32 KB (ATmega328P) of which 0.5 KB used by boot
loader
SRAM 2 KB (ATmega328P)
EEPROM 1 KB (ATmega328P)
Clock Speed 16 MHz
LED_BUILTIN 13
3
Different Types of Arduino Boards
Arduino Uno (R3)
Arduino Nano
Arduino Micro
Arduino Due
LilyPad Arduino Board
Arduino Bluetooth
Arduino Diecimila
RedBoard Arduino Board
Arduino Mega (R3) Board
Arduino Leonardo Board
Arduino Robot
Arduino Esplora
Arduino Pro Mic
Arduino Ethernet
Arduino Zero
Fastest Arduino Board
Introduction to Arduino IDE
The Arduino IDE is an open-source software, which is used to write and upload code
to the Arduino boards. The IDE application is suitable for different operating systems
such as Windows, Mac OS X, and Linux. It supports the programming languages C and
C++. Here, IDE stands for Integrated Development Environment.
4
Simple Program LED Blinking
5
Simple Traffic Light Control Program
Code:
int red = 2 ;
int yellow = 3
; int green =
4 ; void
setup(){
pinMode(red, OUTPUT);
pinMode(yellow,
OUTPUT); pinMode(green,
OUTPUT);
}
void loop(){
digitalWrite(red, 1);
delay(4000);
digitalWrite(yellow, 1);
delay(1000);
digitalWrite(red, 0);
digitalWrite(yellow, 0);
digitalWrite(green, 1);
delay(5000);
digitalWrite(green, 0);
}
6
Embedded ‘C’ Language
Embedded C is most popular programming language in software field for developing
electronic gadgets. Each processor used in electronic system is associated with
embedded software. Embedded C programming plays a key role in performing
specific function by the processor.
The language in which Arduino is programmed is a subset of C and it includes only
those features of standard C that are supported by the Arduino IDE.
C Introduction
What is C?
C is a general-purpose programming language created by Dennis Ritchie at the Bell
Laboratories in 1972.
C is strongly associated with UNIX, as it was developed to write the UNIX operating
system.
Why Learn C?
It is one of the most popular programming language in the world
If you know C, you will have no problem learning other popular programming
languages such as Java, Python, C++, C#, etc, as the syntax is similar
C is very fast, compared to other programming languages,
like Java and Python
C is very versatile; it can be used in both applications and technologies
8
C++ was developed as an extension of C, and both languages have almost
the same syntax
The main difference between C and C++ is that C++ support classes and
objects, while C does not
Get Started
It is not necessary to have any prior programming experience.
There are many text editors and compilers to choose from. In this tutorial, we will
use an IDE (see below).
C Install IDE
An IDE (Integrated Development Environment) is used to edit AND compile the
code.
Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all free,
and they can be used to both edit and debug C code.
We will use Code::Blocks in our tutorial, which we believe is a good place to start.
C Syntax
Example
#include <stdio.h>
int main() {
printf("Hello
World!"); return 0;
}
Example explained
Line 1: #include <stdio.h> is a header file library that lets us work with input
and output functions, such as printf() (used in line 4). Header files add
functionality to C programs.
9
Don't worry if you don't understand how #include <stdio.h> works. Just think of
it as something that (almost) always appears in your program.
Line 2: A blank line. C ignores white space. But we use it to make the code more
readable.
Line 3: Another thing that always appear in a C program, is main(). This is called
a function. Any code inside its curly brackets {} will be executed.
Line
Note5:that:
return 0 ends
Every the main()
C statement function.
ends with a semicolon ;
Line
Note:6:The
Do not
bodyforget
of inttomain()
add the closing
could alsocurly
beenbracket
written}as:
to actually end the main
function.
int main(){printf("Hello World!");return 0;}
Comments in C
Remember: The compiler ignores white spaces. However, multiple lines makes
the code more readable.
Comments can be used to explain code, and to make it more readable. It can also
be used to prevent execution when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by the compiler (will not be
executed).
// This is a comment
Example World!");
printf("Hello
10
C Multi-line Comments
Multi-line comments start with /* and ends with */.
C reserved keywords
The table below lists all keywords reserved by the C language. When the current programming
language is C or C++, these keywords cannot be abbreviated, used as variable names, or used as any
other type of identifiers.
C Variables
Variables are containers for storing data values.
In C, there are different types of variables (defined with different keywords), for
example:
11
To create a variable, specify the type and assign it a value:
Syntax
type variableName = value;
Where type is one of C types (such as int), and variableName is the name of the
variable (such as x or myName). The equal sign is used to assign a value to the
variable.
So, to create a variable that should store a number, look at the following
example:
Example
int myNum;
myNum =
15;
Note: If you assign a new value to an existing variable, it will overwrite the
previous value:
Example
int myNum = 15; // myNum is
15 myNum = 10; // Now myNum
is 10
Output Variables
You learned from the output chapter that you can output values/print text with
the printf() function:
Example
printf("Hello World!");
In many other programming languages (like Python, Java, and C++), you would
normally use a print function to display the value of a variable. However, this is
not possible in C:
12
Example
int myNum = 15;
printf(myNum); // Nothing happens
To output variables in C, you must get familiar with something called "format
specifiers".
Format Specifiers
Format specifiers are used together with the printf() function to tell the
compiler what type of data the variable is storing. It is basically a placeholder for
the variable value.
For example, to output the value of an int variable, you must use the format
specifier %d or %i surrounded by double quotes, inside the printf() function:
Example
int myNum = 15;
printf("%d", myNum); // Outputs 15
Example
// Create variables
int myNum = 5; // Integer (whole
number) float myFloatNum = 5.99; // Floating
point number char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n",
myFloatNum); printf("%c\
n", myLetter);
To combine both text and a variable, separate them with a comma inside
the printf() function:
Example
int myNum = 5;
printf("My favorite number is: %d", myNum);
To print different types in a single printf() function, you can use the following:
13
Example
int myNum = 5;
char myLetter = 'D';
printf("My number is %d and my letter is %c", myNum, myLetter);
Add Variables
You will learn Together
more about Data Types in the next chapter.
Example
int x =
5; int y
= 6;
int sum = x + y;
printf("%d",
sum);
Example
int x = 5, y = 6, z =
50; printf("%d", x + y
+ z);
You can also assign the same value to multiple variables of the same type:
Example
int x, y, z;
x = y = z = 50;
printf("%d", x + y +
z);
C Variable Names
All C variables must be identified with unique names.
Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
14
Example
// Good
int minutesPerHour = 60;
Data Types
As explained in the Variables chapter, a variable in C must be a specified data
type, and you must use a format specifier inside the printf() function to display
it:
Example
// Create variables
int myNum = 5; // Integer (whole
number) float myFloatNum = 5.99; // Floating
point number char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n",
myFloatNum); printf("%c\
n", myLetter);
float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient
for storing 7 decimal digits
double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient
for storing 15 decimal digits
15
char 1 byte Stores a single character/letter/number, or ASCII values
%d or %i int
%f float
%lf double
%c char
%s Used for strings, which you will learn more about in a later chapter
Constants
When you don't want others (or yourself) to override existing variable values, use
the const keyword (this will declare the variable as "constant", which
means unchangeable and read-only):
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable 'myNum'
You should always declare the variable as constant when you have values that are
unlikely to change:
Example
const int minutesPerHour = 60;
const float PI = 3.14;
Notes on Constants
When you declare a constant variable, it must be assigned with a value:
16
const int minutesPerHour;
minutesPerHour = 60; //
error
Good Practice
Another thing about constant variables, is that it is considered good practice to
declare them with uppercase. It is not required, but useful for code readability and
common for C programmers:
Example
Output a number entered by the user:
// Create an integer variable that will store the number we get from the
user
int myNum;
User Input
The scanf() Strings
function takes two arguments: the format specifier of the variable (%d
in the example above) and the reference operator (&myNum), which stores the
memory address of the variable.
You can also get a string entered by the user:
Tip: You will learn more about memory addresses and functions in the
next chapter.
Example
Output the name of a user:
17
// Create a
string char
firstName[30];
Note that you must specify the size of the string/array (we used a very high
Operators
number, 30, but atleast then we are certain it will store enough characters for the
first name), and you don't have to specify the reference operator ( &) when
working with strings in scanf().
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
int myNum = 100 + 50;
Although the + operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a value, or a
variable and another variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 +
250) int sum3 = sum2 + sum2; // 800 (400
+ 400)
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
18
Operator Name Description Example
Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
Example
int x = 10;
Example
int x =
10; x +=
5;
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
19
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
Comparison Operators
Comparison operators are used to compare two values.
Note: The return value of a comparison is either true (1) or false (0).
In the following example, we use the greater than operator (>) to find out if 5 is
greater than 3:
Example
int x =
5; int y
= 3;
printf("%d", x > y); // returns 1 (true) because 5 is greater than 3
== Equal to x == y
!= Not equal x != y
Logical Operators
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns true if both statements are true x < 5 && x < 10
20
! Logical not Reverse the result, returns false if the !(x < 5 && x < 10)
result is true
Sizeof Operator
The memory size (in bytes) of a data type or a variable can be found with
the sizeof operator:
Example
int myInt;
float myFloat;
double
myDouble; char
myChar;
printf("%lu\n", sizeof(myInt));
printf("%lu\n",
sizeof(myFloat)); printf("%lu\
n", sizeof(myDouble));
printf("%lu\n",
sizeof(myChar));
You can use these conditions to perform different actions for different decisions.
The if Statement
Use the if statement to specify a block of C code to be executed if a condition
is true.
21
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
In the example below, we test two values to find out if 20 is greater than 18. If the
Note thatisiftrue
condition is in lowercase
, print letters. Uppercase letters (If or IF) will generate
some text:
an error.
Example
if (20 > 18) {
printf("20 is greater than 18");
}
Example
int x =
20; int y
= 18; if
(x > y) {
printf("x is greater than y");
}
Example explained
In the example above we use two variables, x and y, to test whether x is greater
than y (using the > operator). As x is 20, and y is 18, and we know that 20 is
greater than 18, we print to the screen that "x is greater than y".
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
22
Example
int time = 20;
if (time < 18)
{
printf("Good day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."
Example explained
In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
Example
int time = 22;
if (time < 10)
{
printf("Good morning.");
} else if (time < 20)
{ printf("Good
day.");
} else {
printf("Good evening.");
}
// Outputs "Good evening."
Example explained
In the example above, time (22) is greater than 10, so the first condition is false.
The next condition, in the else if statement, is also false, so we move on to
the else condition since condition1 and condition2 is both false - and print to the
screen "Good evening".
23
However, if the time was 14, our program would print "Good day."
Another Example
This example shows how you can use if..else if to find out if a number is positive or
negative:
Example
int myNum = 10; // Is this a positive or negative number?
if (myNum > 0)
printf("The value is a positive
number."); else if (myNum < 0)
printf("The value is a negative
number."); else
printf("The value is 0.");
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:
Example
int time = 20;
if (time < 18)
{
printf("Good day.");
} else {
printf("Good evening.");
}
Example
int time = 20;
(time < 18) ? printf("Good day.") : printf("Good evening.");
Switch Statement
24
Instead of writing many if..else statements, you can use the switch
executed:
Syntax
switch(expression)
{ case x:
// code block
break
; case
y:
// code block
break
;
default
:
// code block
}
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4;
switch (day)
{ case 1:
printf("Monday"
); break;
case 2:
printf("Tuesday"
); break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday"
); break;
case 5:
printf("Friday"
); break;
case 6:
printf("Saturday"
25
); break;
case 7:
26
printf("Sunday"
); break;
}
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need
for more testing.
The default
of the code inKeyword
A break can save a lot of execution time because it "ignores" the execution of
all the rest the switch block.
The default keyword specifies some code to run if there is no case match:
Example
int day = 4;
switch (day)
{ case 6:
printf("Today is
Saturday"); break;
case 7:
printf("Today is
Sunday"); break;
default:
printf("Looking forward to the Weekend");
}
Loops
Note: The default keyword must be used as the last statement in the switch, and
it does not need a break.
Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more
readable.
27
While Loop
The while loop loops through a block of code as long as a specified condition is true:
while (condition) {
Syntax
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as
a variable (i) is less than 5:
int i = 0;
Example
while (i < 5) {
printf("%d\n",
i); i++;
}
The
Note: DoDo/While Loop
not forget to increase the variable used in the condition ( i++),
otherwise the loop will never end!
The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop as
long as the condition is true.
do {
Syntax
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:
int i = 0;
Example
do {
28
printf("%d\n",
i); i++;
}
while (i < 5);
For
Do not Loop
forget to increase the variable used in the condition, otherwise the loop
will never end!
When you know exactly how many times you want to loop through a block of code,
use the for loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
int i;
for (i = 0; i < 5; i+
+) { printf("%d\n",
i);
}
Example explained
Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been
executed.
Another Example
This example will only print even values between 0 and 10:
29
Example
for (i = 0; i <= 10; i = i +
2) { printf("%d\n", i);
}
Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.
Example
int i;
Continue
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
Example
int i;
30
Break Example
int i = 0;
Continue Example
int i = 0;
Strings
Strings are used for storing text/characters.
Unlike many other programming languages, C does not have a String type to
easily create string variables. However, you can use the char type and create
an array of characters to make a string in C:
To output the string, you can use the printf() function together with the format
specifier %s to tell C that we are now working with strings:
Example
char greetings[] = "Hello
World!"; printf("%s",
greetings);
Access Strings
31
Since strings are actually arrays in C, you can access a string by referring to its
index number inside square brackets [].
Example
char greetings[] = "Hello
World!"; printf("%c",
greetings[0]);
Modify Strings
Note that we have to use the %c format specifier to print a single character.
To change the value of a specific character in a string, refer to the index number,
and use single quotes:
Example
char greetings[] = "Hello
World!"; greetings[0] = 'J';
printf("%s", greetings);
// Outputs Jello World! instead of Hello World!
You should also note that you can to create a string with a set of characters. This
example will produce the same result as the one above:
Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', '
', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
printf("%s", greetings);
Differences
Why do we include the \0 character at the end? This is known as the "null
terminating character", and must be included when creating strings using this
method. It tells C that this is the end of the string.
The difference between the two ways of creating strings, is that the first method is
easier to write, and you do not have to include the \0 character, as C will do it for
you.
32
You should note that the size of both arrays is the same: They both have 13
characters (space also counts as a character by the way), including
the \0 character:
Example
char greetings[] = {'H', 'e', 'l', 'l', 'o', '
', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
char greetings2[] = "Hello World!";
Memory Address
When a variable is created in C, a memory address is assigned to the variable.
The memory address is the location of where the variable is stored on the
computer.
To access it, use the reference operator (&), and the result will represent where the
variable is stored:
Example
int myAge = 43;
printf("%p", &myAge); // Outputs 0x7ffe5367e044
Note: The memory address is in hexadecimal form (0x..). You probably won't get
the same result in your program.
You should also note that &myAge is often called a "pointer". A pointer basically
stores the memory address of a variable as its value. To print pointer values, we
use the %p format specifier.
Creating Pointers
You learned from the previous chapter, that we can get the memory address of a
variable with the reference operator &:
Example
int myAge = 43; // an int variable
33
A pointer is a variable that stores the memory address of another variable as its
value.
A pointer variable points to a data type (like int) of the same type, and is
created with the * operator. The address of the variable you're working with is
assigned to the pointer:
Example
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that
stores the address of myAge
Example explained
Create a pointer variable with the name ptr, that points to an int variable
(myAge). Note that the type of the pointer has to match the type of the variable
you're working with.
Use the & operator to store the memory address of the myAge variable, and assign it
to the pointer.
Dereference
In the example above, we used the pointer variable to get the memory address of
a variable (used together with the & reference operator).
However, you can also get the value of the variable the pointer points to, by using
the * operator (the dereference operator):
Example
int myAge = 43; // Variable
declaration int* ptr = &myAge; //
Pointer declaration
34
printf("%d\n", *ptr);
Note that the * sign can be confusing here, as it does two different things in
our code:
Pointers are one of the things that make C stand out from other programming
languages, like Python and Java.
Note: Pointers must be handled with care, since it is possible to damage data
stored in other memory addresses.
Good To Know: There are three ways to declare pointer variables, but the first
way is mostly used:
Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
To create an array, define the data type (like int) and specify the name of the
array followed by square brackets [].
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
This statement accesses the value of the first element [0] in myNumbers:
35
Example
int myNumbers[] = {25, 50, 75,
100}; printf("%d",
myNumbers[0]);
// Outputs 25
Example
myNumbers[0] = 33;
Example
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d",
myNumbers[0]);
Example
int myNumbers[] = {25, 50, 75,
100}; int i;
36
Example
// Declare an array of four integers:
int myNumbers[4];
// Add elements
myNumbers[0] =
25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
Using this method, you should know the size of the array, in order for the
program to store enough memory.
You are not able to change the size of the array after creation.
C Functions
A function is a block of code which only runs when it is called.
Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.
Predefined Functions
So it turns out you already know what a function is. You have been using it the
whole time while studying this tutorial!
For example, main() is a function, which is used to execute code, and printf() is a
function; used to output/print text to the screen:
Example
int main() {
printf("Hello
World!"); return 0;
}
Create a Function
To create (often referred to as declare) your own function, specify the name of the
function, followed by parentheses () and curly brackets {}:
37
Syntax
void myFunction() {
// code to be executed
}
Example Explained
Call a Function
Declared functions are not executed immediately. They are "saved for later use",
and will be executed when they are called.
To call a function, write the function's name followed by two parentheses () and a
semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is
called:
// Create a function
Example
void myFunction() {
printf("I just got executed!");
}Inside main, call myFunction():
int main() {
myFunction(); // call the
function return 0;
}
Example
void myFunction() {
printf("I just got executed!");
}
38
int main() {
myFunction(
);
myFunction(
);
myFunction(
); return
0;
}
Parameters are specified after the function name, inside the parentheses. You can
add as many parameters as you want, just separate them with a comma:
Syntax
returnType functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
The following function that takes a string of characters with name as parameter.
When the function is called, we pass along a name, which is used inside the
function to print "Hello" and the name of each person.
Example
void myFunction(char
name[]) { printf("Hello
%s\n", name);
}
int main() {
myFunction("Liam")
;
myFunction("Jenny"
);
myFunction("Anja")
; return 0;
}
// Hello Liam
// Hello Jenny
// Hello Anja
Example
void myFunction(char name[], int age) {
printf("Hello %s. You are %d years old.\n", name, age);
}
int main() {
myFunction("Liam",
3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Return
Note that whenValues
you are working with multiple parameters, the function call must
have the same number of arguments as there are parameters, and the
arguments must be passed in the same order.
The void keyword, used in the previous examples, indicates that the function
should not return a value. If you want the function to return a value, you can use a
data type (such as int or float, etc.) instead of void, and use the return keyword
inside the function:
Example
int myFunction(int x) {
return 5 + x;
}
int main() {
printf("Result is: %d", myFunction(3));
return 0;
}
// Outputs 8 (5 + 3)
40
Example
int myFunction(int x, int
y) { return x + y;
}
int main() {
printf("Result is: %d", myFunction(5, 3));
return 0;
}
// Outputs 8 (5 + 3)
Example
int myFunction(int x, int
y) { return x + y;
}
int main() {
int result = myFunction(5, 3);
printf("Result is = %d",
result);
return 0;
}
// Outputs 8 (5 + 3)
Example
// Create a
function void
myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the
function return 0;
}
Declaration: the function's name, return type, and parameters (if any)
41
Definition: the body of the function (code to be executed)
You will often see C programs that have function declaration above main(), and
function definition below main(). This will make the code better organized and
easier to read:
Example
// Function declaration
void myFunction();
// The main
method int
main() {
myFunction(); // call the
function return 0;
}
// Function definition
void myFunction() {
printf("I just got executed!");
}
Another Example
If we use the example from the previous chapter regarding function parameters
and return values:
Example
int myFunction(int x, int
y) { return x + y;
}
int main() {
int result = myFunction(5, 3);
printf("Result is = %d",
result);
return 0;
}
// Outputs 8 (5 + 3)
42
Example
// Function declaration
int myFunction(int, int);
// The main
method int
main() {
int result = myFunction(5, 3); // call the
function printf("Result is = %d", result);
return 0;
}
// Function definition
int myFunction(int x, int
y) { return x + y;
}
Function prototype
A function prototype is simply the declaration of a function that
specifies function's name, parameters and return type. It doesn't
contain function body.
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
return 0;
}
// return statement
43
Recursion
Recursion is the technique of making a function call itself. This technique provides a
way to break complicated problems down into simple problems which are easier to
solve.
Recursion may be a bit difficult to understand. The best way to figure out how it
works is to experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more
complicated. In the following example, recursion is used to add a range of numbers
together by breaking it down into the simple task of adding two numbers:
Example
int sum(int k);
int main() {
int result =
sum(10);
printf("%d",
result); return 0;
}
int sum(int k)
{ if (k > 0)
{
return k + sum(k - 1);
} else {
return
0;
}
}
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers
smaller than k and returns the result. When k becomes 0, the function just returns
0. When running, the program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 +9+8+7+6+5+4+3+2+1+0
Since the function does not call itself when k is 0, the program stops there and
returns the result.
44
The developer should be very careful with recursion as it can be quite easy to slip
into writing a function which never terminates, or one that uses excess amounts of
memory or processor power. However, when written correctly recursion can be a
very efficient and mathematically-elegant approach to programming.
Chapter 4 exercise
1. Arduino sketch esa lHkh code processed gksrs gSa \
a. Top to Bottom
b. Bottom to Top
c. Any Order
d. None of these.
2. Arduino esa fy[ks xy yxHkx lHkh statement ds lkFk lekIr gksuk pkfgy\
a. Comma (,)
b. Colon (:)
c. Semicolon (;)
d. Full stop (.)
3. Advantage of Arduino?
a. Easy to Learn
b. Huge Community ¼fo’kky leqnk;½
c. Many Third-Party Libraries ¼dbZ r`rh;&i{k ykbczsjh½
d. All of the above.
6. Compiler Error is \
a. No Semicolon or Parentheses
b. No Variable Initialization
c. Misspellings and Wrong Capitalization
d. All of the above.
7. fuEufyf[kr esa ls dkSu lk dFku serial communication ds ckjs esa lgh gS\
a. Serial Communication yd device ls nwljs device dks sequentially data Hkstus dh process gSA
b. Serial Communication esa] data bits dks yd device ls nwljs device esa sequentially Hkstk tkrk gSA
c. Communication ds rst lk/ku provide djrk gSA
d. All of the above.
45
a. Slave Mode
b. Master Mode
c. Both (a) and (b)
d. None of these.
9. Arduino program esa default method gS \
a. Only loop()
b. Only setup()
c. setup() and loop()
d. setup() or loop()
10. Module dh xokuk djus ds fyy Arduino esa fdl sign dk mi;ksx fd;k tkrk gS\
a. #
b. $
c. %
d. !
12. Arduino UNO esa mi;ksx fd;k tkus okyk microcontroller D;k gS\
a. ATmega32114
b. ATmega2560
c. ATmega328p
d. None of these.
46
d. None of these.
17. Arduino system ds izR;sd startup ij loop function() fdruh ckj run djrk gS\
a. Depends on setup function()
b. Infinite
c. 3
d. 1
19. yd Arduino UNO board esa fdrus PWM pin gksrs gSa\
a. 6
b. 5
c. 13
d. 14
20. IOT development boards esa PWM signals dk D;k mi;ksx gS\
a. They are used by actuators to have digital input.
b. They are used by sensors to have digital input.
c. They are used by sensors to have analog input.
d. They are used by actuators to have analog output.
47
It takes a lot of hard work to make notes, so if you can pay some fee 100,
नोट्स बनाने में बहुत मेहनत लगी है , इसनलए यनि आप कु छ शुल्क 100, 200 रूपए जो आपको उनि
48