Fund. of IoT LAB - CO 252.pptx

y22co015 18 views 149 slides Aug 06, 2024
Slide 1
Slide 1 of 149
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149

About This Presentation


Slide Content

FUNDAMENTALS OF INTERNET OF THINGS LAB PRUDHVI KIRAN P Assistant Professor, CSE - IoT Dept. R. V. R. & J. C. College of Engineering

TASK 1 Introduction of Arduino IDE Write an arduino program to demonstrate setup () and loop () functions Write an arduino program to demonstrate serial and serial.begin () statements Write an arduino program to demonstrate serial.print () statement Write an arduino program to demonstrate serial.available () statement Write an arduino program to demonstrate serial.read () and serial.write () statements Write an arduino program to demonstrate user defined functions

1. Introduction of Arduino IDE The Arduino Integrated Development Environment (IDE) or Arduino Software, contains a text editor for writing code , message area , text console and toolbar with buttons for common functions and a series of menus. This IDE connects to the Arduino board and uploads program and communicate with it. This IDE is developed/written in Java and Arduino program we write in this IDE is based on C++ . Arduino IDE 2.0.x is latest version as of today (September 2023) and Arduino IDE 1.8.x is most used and discussed further. As open source , all versions source code is hosted on GitHub . Downloading the Arduino IDE 2.0 is done through the Arduino Software page at www.arduino.cc/en/software. Sketch A sketch is a program written in the Arduino IDE. Sketches can be saved on the development computer as text files with the file extension . ino (Versions of the Arduino Software (IDE) prior to 1.0 saved sketches with the extension . pde .) 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 at menu bar or from the Open button on the toolbar .

Verify Upload to Board New Open Save MENU BAR TOOL BAR FILE NAME | IDE VERSION SERIAL MONITOR SKETCH EDITOR BOARD & PORT DETAILS TEXT CONSOLE (SHOWS ERRORS) STATUS BAR (UPLOADING STATUS) SKETCH TAB MENU CODE LINES SKETCH FILE TAB

1 - FILE 2 - EDIT 3 - SKETCH 4 - TOOLS 5 - HELP https://docs.arduino.cc/software/ide-v1/tutorials/arduino-ide-v1-basics Detailed information on Arduino IDE’s Menu Bar MENU BAR

SERIAL MONITOR The Serial Monitor is an essential tool when creating projects with Arduino. It can be used as a debugging tool or to communicate directly with the Arduino board. 'baud rate' of the connection. This is how fast the data is to be sent. You can change this to a higher value, but you will also have to change the Arduino Serial monitor to the same value. clears the serial monitor Look after print pattern print with time stamp page scrolls automatically Send the data to board Type the data that should be sent to board data from board is printed here connected port

Open https://www.arduino.cc/, and click on "Software" in the menu tab. Search for "Legacy IDE (1.8.X)", under that, you can see the available version of 1.8. Beside that, you can click on the desired operating system, and click on "just download" button and your file will be downloaded. Install the downloaded setup file, following the instructions displayed. Note that it's a quite easy procedure, where you have to just click few buttons, displayed Infront of you. Installation will be finished with displaying the finished acknowledgement. Now open the installed IDE and connect the Arduino UNO board to the computer using the USB type b cable. You may see a popup of new device on your computer screen or you may hear a device connection acknowledgement from computer. Now You can see the "Power LED" on board is switched on. This indicates that, the board is working. Now go to "Tools" in menu bar and clock on "Board" and click on "Arduino AVR Boards" and select "Arduino UNO". Again go to "Tools" and click on "Port" and select the appropriate port. And you can see the board connection details at the bottom of the IDE. Now you are ready to upload your first program in to the Arduino UNO. STEPS TO CONNECT ARDUINO UNO BOARD TO ARDUINO IDE 1.8.X

UNDERSTANDING ARDUINO’S SERIAL COMMUNICATION Even though the Arduino board is connected to your computer with a USB cable, the communication between the microcontroller on the Arduino Board and the IDE on your computer is as though the microcontroller was connected to a real serial port on your computer. So we see COM Ports usage in IDE. To understand this, open the device manager in your PC after connecting Arduino Board, there under “Ports (COM & LTP)” you can see the name of the Arduino board which is connected and the port assigned to that Arduino board. (as shown in screen shot). Sometimes, when we are not sure, whether the board is connected or not, then we can check here in device manager, whether it is connected or not and you can also know, for which port, the Arduino board is connected. And also in case of any driver installation is required, it will be shown here.

2. Write an arduino program to demonstrate setup () and loop () functions setup() As the void setup function is called only once at the very beginning of the program, this will be the place to: Initialize variables’ values. Setup communications (ex: Serial). Setup modes for digital pins (input/output). Initialize any hardware component (sensor/actuator) plugged to the Arduino, etc. The code inside the void setup will be executed once, and only once, at the beginning of the program. loop() Now, in the void loop you’ll write your main program, knowing that the initialization is already done. In this function, always keep in mind that the last line is followed by the first line! As for void setup, there’s no need to write all the code directly in the function. You can create as many other functions as you want, and call those functions in the void loop. The code inside the void loop will be executed in loop, until you: Power off the Arduino board or Restart the Arduino program - by pressing the reset button on Arduino board.

3. & 4. Serial and S erial.begin (), Serial.print () statements Serial.begin() & Serial.print () Serial communication is a communication technique used in telecommunications wherein data transfer occurs by transmitting data one bit at a time in a sequential order over a computer bus or a communication channel. It is the simplest form of communication between a sender and a receiver. The serial communication is a simple scheme that uses the UART (Universal Asynchronous Receiver/Transmitter) on the Microcontroller. This serial communication is used for communication between the Arduino board and a computer or other devices. All Arduino boards have at least one serial port (Rx, Tx is represented on board), and some have several. On Arduino Uno, pins 0 (Rx - Receiver) and 1 (Tx - Transmitter) are used for UART communication with the computer. Connecting anything to these pins can interfere with that communication which may leads to failed sketch uploads to the board. Arduino Serial Library is a set of serial communication tools. It has various functions to accomplish simple to complex tasks; few of them are; available() read(), write(), print() & println ()

Serial.begin() establishes serial communication between your Arduino board and another device. The most common use of serial communication you will establish is between your Arduino and your computer via a USB cable. The most common reason to use serial.begin () is when you want to output some information from your Arduino to your computer screen. The function used to display text on your computer screen from your Arduino board is the serial.print () function. Serial.begin() function is kept inside of the setup() function, as setup() only runs once, and since you’ll only need to establish the Serial Communication one time. The Serial.begin( ) also sets the baud rate for serial data communication; Serial.begin(9600), the 9600 is the baud rate and this baud rate signifies the data rate in bits per second. The default baud rate in Arduino is 9600 bps (bits per second). We can specify other baud rates as well, such as 4800, 14400, 38400, 28800, etc. If you are using the Arduino IDE Serial Monitor window to read the information from your Arduino, then you can use the baud rate drop down to set the baud rate. The baud rate mentioned in the Serial.begin() and the baud rate set in the serial monitor's drop down should be same. If these two values don’t match - you may see the garbage values.

//Sample Sketch int counter; void setup() { Serial.begin (9600); counter = 10; Serial.print ("Counter: "); Serial.println (counter); } void loop() { counter++; Serial.print ("Counter: "); Serial.println (counter); delay(1000); } Setup() loop() Global variable (can be used in setup() & loop()) Observed Output (In Serial Monitor)

5. & 6.Demonstrate serial.available () , serial.read () and serial.write () statements Serial.available () Serial.available () returns the number of characters (i.e. bytes of data) which have arrived in the serial buffer and that are ready to be read. Serial.available () refers the data that’s already arrived and stored in the serial receive buffer (which holds 64 bytes). Serial.available ( ) function inherits from the utility class called stream. The stream is only invoked when the function relying on it is called. //Sample Sketch int a; void setup() { Serial.begin(9600); a = Serial.available (); Serial.print ("Bytes in Serial Buffer: "); Serial.println (a); } void loop() {} Observed Output (In Serial Monitor)

Serial.available () with Serial.read () Consider the same example we have discussed in Serial Receive Buffer concept, “Sub Sandwich” is still sitting there in the serial receive buffer. Serial.available () would return the number 12; that’s 1 for each remaining character in the buffer. If all you had in the serial receive buffer was “ andwich ” then serial.available () would return the value 7. Usage! Serial.available () is a quick and easy way to know if you have data in the serial receive buffer. The logic would look like this: IF the return value of Serial.available () is greater than 0, THEN part of our message is still sitting in the serial receive buffer. By using the Serial.available () as a condition statement for Serial.read (), we will read all the data and print it on the serial monitor using Serial.print () statement. Getting back to the example “Sub Sandwich” is still sitting there in the serial receive buffer. And this will be completely read and will be printed; when the appropriate code is written in the void loop(). The example and the working scenario presented above is mainly for the understanding purposes. The practical coding environment may look different.

//Sample Sketch char incomingByte = 0; void setup() { Serial.begin(9600); } void loop() { if ( Serial.available () > 0) { incomingByte = Serial.read (); Serial.print ("I received: "); Serial.println ( incomingByte ); } } Observed Output (In Serial Monitor) Character “a” is entered in serial monitor and sent to board

//Sample Sketch char incomingByte = 0; int a; void setup(){ Serial.begin(9600); } void loop(){ if ( Serial.available () > 0){ a = Serial.available (); Serial.print ("Bytes in Serial Receive Buffer: "); Serial.println (a); incomingByte = Serial.read (); Serial.print ("I received: "); Serial.println ( incomingByte ); a = Serial.available (); Serial.print ("Bytes in Serial Receive Buffer: "); Serial.println (a); } } Observed Output (In Serial Monitor) Character “1” is entered in serial monitor and sent to board

Serial.readString () It reads the incoming serial data from the serial buffer in the string. The String data type is used here. //Sample Sketch String b; int a; void setup( ) { Serial.begin(4800); } void loop( ) { while( Serial.available ( ) ) { a = Serial.available (); Serial.print ("Bytes in Serial Receive Buffer: "); Serial.println (a); b = Serial.readString ( ); Serial.print ("Bytes Received: "); Serial.println (b); a = Serial.available (); Serial.print ("Bytes in Serial Receive Buffer: "); Serial.println (a); } } Observed Output (In Serial Monitor) String “ hai RVRJCCE” is entered in serial monitor and sent to board

Serial.write () //Sample Code void setup() { Serial.begin(9600); } void loop() { char data = 0; if( Serial.available ()>0) { data = Serial.read (); Serial.print ("Data Received is : "); Serial.write (data); } } Observed Output (In Serial Monitor) “1” is entered in serial monitor and sent to board Arduino Serial Write is used to write some data on the Serial Port. Serial.write sends bytes to the serial port while Serial.print sends ASCII characters so people can read easily.

7. Write an arduino program to demonstrate user defined functions User Defined Functions There are two required functions in an Arduino sketch or a program i.e. setup () and loop(). Other functions must be created outside the brackets of these two functions. A function is declared outside any other functions, above or below the loop function. //Sample Sketch int sum_func (int x, int y) { int z = 0; z = x+y ; return z; } void setup () { Serial.begin(9600); int result = 0; result = sum_func (5,6); Serial.println (result);} void loop () { } Observed Output (In Serial Monitor)

TASK 2 Write an arduino program to demonstrate data types Write an arduino program to demonstrate variables Write an arduino program to demonstrate constants Write an arduino program to demonstrate operators

8. Write an arduino program to demonstrate data types Arduino Data Types play an important role in Arduino Programming. Data Types are different on the nature of element storing in them. Data type is like a place, so when we initialize our variable then we tell our compiler that our newly introduced integer is of which type. Is it an integer or it has decimal as well in it or its some character like A, B, C etc. Arduino Data Types are almost similar to C++ Data Types because it roughly follows the same syntax. The following table provides all the data types that you will use during Arduino programming;

9. Write an arduino program to demonstrate variables A variable is a place to store a piece of data. It has a name, a value, and a type. Variable will have a property called scope, which refers to Local or Global. Variables declared inside a function (setup()/loop()/other user defined functions), are called local variables. Variables declared outside of all function are called global variables. A global variable can be accessed by any function. unlike local, which are not known to function outside their own. //Sample Sketch int z; Void setup () { } Void loop () { int x,y ; x = 0; y = 0; actual initialization z = 10; } Global Variable Local Variables

10. Write an arduino program to demonstrate constants The constants in Arduino are defined as the predefined expressions. It makes the code easy to read. The name const represents the constant keyword. It further makes the variable as 'read-only'. The variable will function the same as other variables, but its value cannot be changed, it remains constant. //Sample Sketch const float x = 5.68; float y; void setup() { Serial.begin(9600); y = x * 2; Serial.println (y); x=4.5; } void loop() { } Attempted to change the value of constant, this will result in error, saying that, it’s a read only variable. Constant can be used like other variables. Declared as constant/read-only, and it can’t be changed. Observed Output (text/error console)

Logical level Constants The logical level constants are true or false. The value of true and false are defined as 1 and 0. Any non-zero integer is determined as true in terms of Boolean language. The true and false constants are type in lowercase rather than uppercase. Pin level Constants The digital pins can take two value HIGH or LOW. In Arduino, the pin is configured as INPUT or OUTPUT using the pinMode() function. The pin is further made HIGH or LOW using the digitalWrite () function. LED_BUILTIN Constant The Arduino boards have built-in LED connected in series with the resistor. The particular pin number is defined with the constant name called LED_BUILTIN. Most Arduino boards have the LED_BUILTIN connected to Pin number 13. #define Allows the programmer to give a name to a constant value before the program is compiled. The compiler will replace references to these constants with the defined value at compile time. Syntax : #define nameOFconstant value ( Example : #define LEDpin 12)

25 11. Write an arduino program to demonstrate operators The operators are widely used in Arduino programming from basics to advanced levels. It plays a crucial role in every programming concept like C, C++, Java, etc. The operators are used to solve logical and mathematical problems. For example, to calculate the temperature given by the sensor based on some analog voltage. The types of Operators classified in Arduino are: Arithmetic Operators Compound Operators Boolean Operators Comparison Operators Bitwise Operators Arithmetic Operators Assignment ‘=‘ (Example - a = b) Addition '+’ (Example - a = b + 2017) Subtraction '-’ (Example - b = 2017 - a) Multiplication '*’ (Example - d = 2.5 * e) Division '/’ (Example - e = d / 2.5) Remainder '%’ (Example - f = d % 2.5)

Campound Operators b + + (Here, b = b + 1. It is called the increment operator.) b + = (For example, b + = 4. It means, b = b+ 4.) b - - (Here, b = b - 1. It is called as the decrement operator.) b - = (For example, b - = 3. It means, b = b - 3.) b * = (For example, b * = 6. It means, b = b * 6.) b / = (For example, b / = 5. It means, b = b / 5.) b % = (For example, b % = 2. It means, b = b % 2.) Now, let's use the above operators with two variables, b and c. b + = c ( that represents b = b + c) b - = c ( that represents b = b - c) b * = c ( that represents b = b * c) b / = c ( that represents b = b / c) b % = c ( that represents b = b % c) Boolean Operators 1. Logical AND ( & & ) The result of the condition is true if both the operands in the condition are true. Consider the example: if ( a = = b & & b = = c ) - this is true if both conditions are true. If any of the conditions is false, the statement will be false.

2. Logical OR ( | | ) The result of the condition is true, if either of the variables in the condition is true. Consider the below example. if ( a > 0 | | b > 0 ) The above statement is true, if either of the above condition ( a> 0 or b > 0 ) is true. 3. NOT ( ! ) It is used to reverse the logical state of the operand. For example, a ! = 2. The NOT operator returns the value 1 or TRUE when the specified operand is FALSE. It also reverses the value of the expression. Comparision Operators 1. less than ( < ) The less than operator checks that the value of the left operand is less than the right operand. The statement is true if the condition is satisfied. 2. greater than ( > ) The less than operator checks that the value of the left side of a statement is greater than the right side. The statement is true if the condition is satisfied. For example, a > b. If a is greater than b, the condition is true, else false.

3. equal to ( = = ) It checks the value of two operands. If the values are equal, the condition is satisfied. For example, a = = b. The above statement is used to check if the value of a is equal to b or not. 4. not equal to ( ! = ) It checks the value of two specified variables. If the values are not equal, the condition will be correct and satisfied. For example, a ! = b. 5. less than or equal to ( < = ) The less or equal than operator checks that the value of left side of a statement is less or equal to the value on right side. The statement is true if either of the condition is satisfied. For example, a < = b. It checks the value of a is less or equal than b. 6. greater than or equal to ( > = ) The greater or equal than operator checks that the value of the left side of a statement is greater or equal to the value on the right side of that statement. The statement is true if the condition is satisfied. For example, a > = b. It checks the value of a is greater or equal than b. If either of the condition satisfies, the statement is true.

Bitwise Operators The Bitwise operators operate at the binary level. These operators are quite easy to use. There are various bitwise operators. Some of the popular operators are listed below: 1. bitwise NOT ( ~ ) It reverses the input bits. Example: INPUT - 0 0 1 1 (decimal value 3) OUTPUT - 1 1 0 0 (decimal value is 12)

TASK 3 Write an arduino program to demonstrate if statements Write an arduino program to demonstrate switch case Write an arduino program to demonstrate loops Write an arduino program to demonstrate arrays

12. Write an arduino program to demonstrate if statements Control statements are the statements that change the flow of execution of statements. Control statements are used when the execution of the code is controlled by some conditional statements. These control statements can be implemented by different statements like if statements, if-else statements, and switch-case statements. if statement The “if statement” is the simplest form of the control statement in which the statements are written in the body of “if statement”, only if the condition is true then statements in the body will be executed else the compiler executes the next statements. //Sample Sketch int a = 6; int b = 4; void setup() { Serial.begin (9600); } void loop()

{ if (a > b ) { Serial.println ( " a is greater than b "); } if (b > a ) { Serial.println ( " b is greater than a "); } } Observed Output (In Serial Monitor)

if-else statement The “if-else statements” is another type of control statement and the advanced form of “if statements”, works as “either-or” like if one scenario is false it will execute something else. Mostly, it is used in controlling the operation by using a check on it. For example, if the temperature of a room is below 30 degrees, turn on the green LED which means the temperature is normal, or turn on the red LED which means the temperature is above 30 degrees. Sample Sketch int a = 5; int b= 6; void setup ( ) { Serial.begin ( 9600 ); } void loop ( ) { if ( a > b ) {

Serial.println ( " a is greater " ); } else { Serial.println ( " a is smaller " ); } } Observed Output (In Serial Monitor)

35 13. Write an arduino program to demonstrate switch case In control statements of Arduino, one is the switch-case statements by which we can control the flow of the program. In switch-case statements, different cases are declared, if any of them becomes true, that case's body is executed and the compiler breaks and goes out of the whole switch-case body, without touching other case's. //Sample Sketch void setup() { Serial.begin (9600); int a = 1; switch(a) // the case matching the value in the declared variable will run { case 1: Serial.println (" Case 1 matches"); break; case 2: Serial.println (" Case 2 matches"); break;

case 3: Serial.println (" Case 3 matches"); break; default: Serial.println (" default matches"); break; } } void loop() { } Observed Output (In Serial Monitor)

//Sample Code - LED operation with Switch Case const int ledPIN = 13; char data; int option; void setup() { Serial.begin (9600); pinMode ( ledPIN , OUTPUT); } void loop(){ data = Serial.read (); if(data == '0') { option = 0; }else if(data == '1') { option = 1; }else if(data == '2') { option = 2;

} switch (option){ case 0: // LED OFF digitalWrite ( ledPIN , LOW); break; case 1: //LED ON digitalWrite ( ledPIN , HIGH); break; case 2: // LED BLINK digitalWrite ( ledPIN , HIGH); delay(200); digitalWrite ( ledPIN , LOW); delay(200); break; }} Observed Output (In Serial Monitor) When entered 1 - LED switched ON When entered 2 - LED started BLINKING When entered 0 – LED switched OFF

39 14. Write an arduino program to demonstrate loops Loops are used to control the flow of a program. In a loop, a block of code is executed over and over again. Each cycle of the loop is called an iteration of the loop. Depending on certain conditions that you can define in the code, you can control whether the program enters the loop or not. Every Arduino sketch has at least one loop - the main loop or void loop() section. But it can be very useful to have other loops operating inside of the main loop. While loop If the condition is true, the program will enter the body of the while loop and execute the body code in a loop for as long as the condition remains true. If the condition is false, the program will skip the while loop and continue to the next line of code. //Sample Sketch int a = 0; void setup() { Serial.begin (9600); while( a < 5) {

Serial.println ("Welcome to RVRJCCE"); a = a + 1; } } void loop() { } Observed Output (In Serial Monitor)

Do While loop Do while loops work the same way as regular while loops, except that the body code is executed before the test for the condition occurs. So even if the condition is false, the code in the body will be run at least once. //Sample Sketch void setup (void) { int b = 0; int c; Serial.begin (9600); do { c=b++; Serial.print ("the value of c is :"); Serial.println (c); }while( c <= 20 ); } void loop(void){ }

Observed Output (In Serial Monitor)

For loop For loops are frequently used to increment and decrement counters, or to initialize large numbers of pins at the same time. For loops evaluate a set of three parameters - the initialization value, the condition, and the iteration. //Sample Sketch void setup() { Serial.begin (9600); } void loop() { int i = 0; for( i = 0; i < 10; i ++) { Serial.println ( i ); } while( i < 20) { i = i+1; Serial.println ( i );

Observed Output (In Serial Monitor) } }

15. Write an arduino program to demonstrate arrays Arrays are like variables - they can store sensor readings, text strings, and Boolean values like high and low. But a variable can only store one value at a time. Arrays can store multiple values at the same time. If you think of a variable as a storage container for data, arrays are like that container but with dividers that you can use to store multiple pieces of data. //Sample Sketch void setup() { int my_array [5]; int i ; Serial.begin (9600); my_array [0] = 23; my_array [1] = 1001; my_array [2] = 9; my_array [3] = 1234; my_array [4] = 987; for ( i = 0; i < 5; i ++) { Serial.println ( my_array [ i ]);

} } void loop() { } Observed Output (In Serial Monitor)

//Sample Sketch - Multiple LED Blink with Array int ledPins [6] = {13, 12, 11}; void setup() { for (int i = 0; i < 3 ; i ++) { pinMode ( ledPins [ i ], OUTPUT); } } void loop() { for (int j = 0; j < 3; j++ ) { digitalWrite ( ledPins [j], HIGH); delay(500); digitalWrite ( ledPins [j], LOW); delay(500); }} Observed Output (In Serial Monitor) Connected LEDs will blink one after another, with appropriate delay of 1 Second.

CIRCUIT DIAGRAM - MULTIPLE LED BLINK WITH ARRAY

TASK 4 Write an arduino program to demonstrate strings Write an arduino program to demonstrate string object Write an arduino program to demonstrate time based functions Write an arduino program to demonstrate random numbers generation

16. Write an arduino program to demonstrate strings Strings are used to store text. They can be used to display text on an LCD or in the Arduino IDE Serial Monitor window. There are two types of strings in Arduino programming; Arrays of characters, which are the same as the strings used in C programming. The Arduino String, which lets us use a string object in a sketch. Arrays of characters, which are the same as the strings used in C programming The first type of string in Arduino is a series of characters of the type char. I.e., it is just an array; a consecutive series of the char type of variable stored in memory. A string is an array of char variables. Note that, A string is a special array that has one extra element at the end of the string, which always has the value of 0 (zero). This is known as a "null terminated string". //Sample Sketch void setup() { char my_str [6]; Serial.begin (9600); my_str [0] = 'H'; my_str [1] = 'e'; my_str [2] = 'l’;

my_str [3] = 'l'; my_str [4] = 'o'; my_str [5] = 0; // 6th array element is a null terminator Serial.println ( my_str ); } void loop() { } Observed Output (In Serial Monitor)

ARRAYS //Sample Sketch void setup() { String my_str = "This is my string."; Serial.begin (9600); // (1) print the string Serial.println ( my_str ); // (2) change the string to upper-case my_str.toUpperCase (); Serial.println ( my_str ); my_str = "My new string."; // (3) overwrite the string The Arduino String, which lets us use a string object in a sketch. An object is a construct that contains both data and functions. A String object can be created just like a variable and assigned a value or string. The String object contains functions (which are called "methods" in object oriented programming (OOP)) which operate on the string data contained in the String object. 17. Write an arduino program to demonstrate string object

Serial.println ( my_str ); // (4) replace a word in the string my_str.replace ("string", "Arduino sketch"); Serial.println( my_str ); // (5) get the length of the string Serial.print ("String length is: "); Serial.println( my_str.length ()); } void loop() { } Observed Output (In Serial Monitor)

ARRAYS delay () function It pauses the program for the amount of time (in milliseconds) specified as parameter. The way the delay() function works is pretty simple. It accepts a single integer (or number) argument. This number represents the time (measured in milliseconds). delayMicroseconds () function It pauses the program for the amount of time (in milliseconds) specified as parameter. The delayMicroseconds() function accepts a single integer (or number) argument. There are a thousand microseconds in a millisecond, and a million microseconds in a second. millis () function This function is used to return the number of milliseconds at the time, the Arduino board begins running the current program. This number overflows i.e. goes back to zero after approximately 50 days. micros () function The micros() function returns the number of microseconds from the time, the Arduino board begins running the current program. This number overflows i.e. goes back to zero after approximately 70 minutes. Syntax delay ( ms ) ; Syntax delayMicroseconds (us) ; Syntax millis () ; Syntax micros () ; 18. Write an arduino program to demonstrate time based functions

//Sample Sketch - delay() int led1 = 11; void setup() { pinMode(led1, OUTPUT); } void loop() { digitalWrite ( ledPin , HIGH); delay(1000); digitalWrite ( ledPin , LOW); delay(1000); } //Sample Sketch - delayMicroseconds () int led1 = 11; void setup() { pinMode(led1, OUTPUT); }

void loop() { digitalWrite ( ledPin , HIGH); delayMicroseconds (10000); digitalWrite ( ledPin , LOW); delayMicroseconds (10000); } //Sample Sketch - millis () & micros() void setup() { Serial.begin (9600); Serial.println ( millis ()); Serial.println (micros()); } void loop() {}

Observed Outputs (In Serial Monitor)

19. Write an arduino program to demonstrate random numbers generation First, understand why we need to generate the pseudo-random numbers? In real life, we have to generate random codes for verification purposes. Similarly, in digital programming, we may have the scenario to generate random passwords. For this purpose, we have to generate the random numbers in Arduino. To generate random numbers, you can use Arduino random number functions. We have two functions; random() randomSeed (seed) random() The random function generates pseudo-random numbers. This can be done in one way, where max random range number can be specified or min and max range can be specified. Following is the syntax; long random(max) // it generate random numbers from 0 to max long random(min, max) // it generate random numbers from min to max Example long random(500) // it generate random numbers from 0 to 500 long random(10, 15) // it generate random numbers from 10 to 15 random()

//Sample Sketch - random(max) void setup(){ Serial.begin (9600);} void loop(){ long randomNumber = random(300); Serial.print ("The Random Number is = "); Serial.println( randomNumber ); delay(1000);} Observed Outputs (In Serial Monitor)

//Sample Sketch - random( min,max ) void setup(){ Serial.begin (9600);} void loop(){ long randomNumber = random(2,5); Serial.print ("The Random Number is = "); Serial.println ( randomNumber ); delay(1000);} Observed Outputs (In Serial Monitor)

randomSeed (seed) The function randomSeed (seed) resets Arduino’s pseudorandom number generator. Although the distribution of the numbers returned by random() is essentially random, the sequence is predictable. ; in this case we should reset the generator to some random value. It can be done using analogRead () - If you have an unconnected analog pin, it might pick up random noise from the surrounding environment. These may be radio waves, cosmic rays, electromagnetic interference from cell phones, fluorescent lights and so on. So we will get the random numbers generated by the unused analog pin. Syntax randomSeed ( analogRead (analog pin number)); // randomize using noise from specified analog pin Example randomSeed ( analogRead (5)); // randomize using noise from analog pin 5 //Sample Sketch - randomSeed (seed) long randNumber ; void setup() { Serial.begin (9600); randomSeed ( analogRead (0)); }

void loop() { randNumber = random(300); Serial.println( randNumber ); delay(50); } Observed Outputs (In Serial Monitor)

//Sample Sketch - All Random Functions long randNumber ; void setup() { Serial.begin (9600); randomSeed ( analogRead (0));} void loop(){ Serial.print ("random1="); randNumber = random(300); Serial.println ( randNumber ); Serial.print ("random2="); randNumber = random(10, 20); Serial.println ( randNumber ); delay(1000);} Observed Outputs (In Serial Monitor)

TASK 5 Write an arduino program to demonstrate digital I/O functions Write an arduino program to demonstrate analog I/O functions

20. Write an arduino program to demonstrate digital I/O functions pinMode() The pins on the Arduino board can be configured as either inputs or outputs. The pinMode() function is used to configure a specific pin to behave either as an input or an output. T he pinMode () function is usually performed in the void setup() fragment of the code. To use the pinMode function, in the setup of your code, the syntax is; pinMode (pin, mode) where pin refer to the pin number and mode refers to the designation of either INPUT, or OUTPUT. Arduino pins are by default configured as inputs, so they do not need to be explicitly declared as inputs with pinMode() when you are using them as inputs. digitalWrite () Write a HIGH or a LOW value to a digital pin. If the pin has been configured as an OUTPUT with pinMode (), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW. digitalRead () Reads the value from a specified digital pin, either HIGH or LOW. If the pin isn’t connected to anything, digitalRead () can return either HIGH or LOW (and this can change randomly).

//Sample Sketch - digitalWrite () void setup() { pinMode (13, OUTPUT); } // sets the digital pin 13 as output void loop() { digitalWrite (13, HIGH); // sets the digital pin 13 on delay(1000); // waits for a second digitalWrite (13, LOW); // sets the digital pin 13 off delay(1000); } // waits for a second //Sample Sketch - digitalRead () int ledPin = 13; // LED connected to digital pin 13 int inPin = 7; // pushbutton connected to digital pin 7 int val = 0; // variable to store the read value void setup() { pinMode ( ledPin , OUTPUT); // sets the digital pin 13 as output pinMode ( inPin , INPUT); } // sets the digital pin 7 as input void loop() { val = digitalRead ( inPin ); // read the input pin digitalWrite ( ledPin , val ); } // sets the LED to the button's value

21. Write an arduino program to demonstrate analog I/O functions analogRead () The analogRead ( ) function reads the value from the specified analog pin present on the particular Arduino board. The ADC (Analog to Digital Converter) on the Arduino board is a multichannel converter. It maps the input voltage and the operating voltage between the values 0 and 1023. The operating voltage can be 5V or 3.3V. The time duration to read an analog input signal on the boards (UNO, Mega, Mini, and Nano) is about 100 microseconds or 0.0001 seconds. //Sample Sketch - analogRead () int AnaPin = A3; // Analog pin A3 is specified here int value = 0; // variable declared to store the value read void setup(){ Serial.begin (9600); // It sets the serial rate at bps } void loop(){ value = analogRead ( AnaPin ); // It reads the input pin Serial.println (value); }

Observed Outputs (In Serial Monitor)

//Sample Code - LM 35 Temp Sensor with analogRead () void setup() { Serial.begin (9600); } void loop() { int temp_adc_val ; float temp_val ; // Read Temperature temp_adc_val = analogRead (A0); // Convert adc value to equivalent voltage temp_val = ( temp_adc_val * 4.88); // LM35 gives output of 10mv/°C temp_val = ( temp_val /10); Serial.print ("Temperature = "); Serial.print ( temp_val ); Serial.print (" Degree Celsius\n"); delay(1000);}

CIRCUIT DIAGRAM - TEMPERATURE SENSOR

Observed Outputs (In Serial Monitor)

analogWrite () Writes an analog value (PWM wave) to PWM pin, not analog pins. analogWrite () can not be used with regular analog pins (A0 - A5); that’s why those pins are termed as analog input pins, not analog input/output pins. analogWrite () is used with PWM pins to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite (), the pin will generate a steady rectangular wave of the specified duty cycle until the next call to analogWrite (). //Sample Sketch int ledPin = 9; // LED connected to digital pin 9 int analogPin = 3; // potentiometer connected to analog pin 3 int val = 0; // variable to store the read value void setup() { pinMode ( ledPin , OUTPUT); // sets the pin as output } void loop() { val = analogRead ( analogPin ); // read the input pin analogWrite ( ledPin , val /4); // analogRead values go from 0 to 1023, analogWrite values from 0 to 255 }

CIRCUIT DIAGRAM - LED BRIGHTNESS WITH POTENTIOMETER

Observed Outputs (In Serial Monitor) LED brightness varies with potentiometer usage. Brightness increases at potentiometer turned towards maximum and brightness decreases when potentiometer turns towards minimum.

map() Function Re-maps a number from one range to another. That is, a value of ‘from Low’ would get mapped to ‘to Low’, a value of ‘from High’ to ‘to High’, values in-between to values in-between, etc. Syntax map(value, fromLow , fromHigh , toLow , toHigh ) Example Instance - Motor speed control using Potentiometer We can sample the potentiometer with one of Arduino’s analog inputs, which have a resolution of 1024 values (0 to 1023). For this purpose, we use the analogRead () function. Next, to control the motor, we use Pulse Width Modulation which has a resolution of 256 values (0 to 255). For this purpose, we use the analogWrite () function. Now, the value we measure in the analog inputs, should be converted in to a proportional value inside the PWM range of values. This can be done using map(). Sample Sketch //Sample Sketch void setup(){ Serial.begin (9600); } void loop(){ int val = analogRead (A0);

val = map( val , 0, 1023, 0, 255); Serial.println ( val ); delay(1000); } Observed Outputs (In Serial Monitor) Outputs - map() function disabled

TASK 6 Write an arduino program to demonstrate an LED Write an arduino program to demonstrate the 7-segment display. Write an arduino program to demonstrate button Write an arduino program to demonstrate switch

22. Write an arduino program to demonstrate an LED LED (Light Emitting Diode) is an electronic device, which emits light when the current passes through its terminals. LED's are used in various applications. It is also used as an ON/OFF indicator in different electronic devices. Flat Edge Flag Shape TOP VIEW SIDE VIEW LEDs ON ARDUINO UNO R3 BOARD EXTERNAL LED ON-BOARD LED (13 PIN) POWER LED LED SYMBOL

//Sketch - LED BLINK void setup() { pinMode (3, OUTPUT); } void loop() { digitalWrite (3, HIGH); delay(1000); digitalWrite (3, LOW); delay(1000); } Observed Output LED connected to PIN 3 is switched on for one second; Switched off for one second; is repeated in loop, till the board is connected to power.

//Sample Sketch - LED Blink without delay() unsigned long previousMillis = 0; int ledState = LOW; long interval = 1000; void setup() { Serial.begin (9600); pinMode (3, OUTPUT);} void loop() { unsigned long currentMillis = millis (); if ( currentMillis - previousMillis >= interval) { Serial.println ( previousMillis ); Serial.println ( currentMillis ); previousMillis = currentMillis ; if( ledState == LOW) ledState = HIGH; else ledState = LOW; digitalWrite (3, ledState ); }}

Observed Outputs (In Serial Monitor)

23. Write an arduino program to demonstrate the 7-segment display 7-segment displays are made up of 8 LED segments . They are used to display Numbers (0-9) and certain Alphabets, with 7 segments and 1 segment is exclusive for decimal point (DP). Each of the seven LEDs is called a segment because when illuminated the segment forms part of a numerical digit to be displayed. These individually LED pins (7 Pins) are labelled from A through to G representing each individual LED. One Pin is for DP and 2 Pins (one in top and one in bottom) are connected together and wired to form a common pin (Common Cathode/Anode). Totally 10 pins are seen on 7-segments LED. There are two types of LED 7-segment displays: common cathode (CC) and common anode (CA). The difference between the two displays is the common cathode has all the cathodes of the 7-segments connected directly together and the common anode has all the anodes of the 7-segments connected together. For Common Cathode, A to G pins are connected to 7 GPIO pins and DP can be connected to another GPIO. As this is a common cathode, one of the two available common pin should be connected to Ground Pin. COMMON COMMON

For Common Anode, A to G pins are connected to 7 GPIO pins and DP can be connected to another GPIO. As this is a common anode, one of the two available common pin should be connected to voltage Pin. For both common anode and common cathode, as these segments works like normal LED, we have to connect 8 individual resistors (can use 220 ohms resistor) for all the pins (A to G & DP)). COMMON COMMON

UNDERSTANDING PROGRAMMING OF A 7 SEGMENT LED Program structure is same as LED program, based on the number/character we want to get displayed, we will instruct the segments to on/off. For example if we want to display value 2, then we will send the instructions to light up (HIGH) A,B,G,E,D segments and off (LOW) remaining. Writing Arduino sketch for Common Cathode 7 segment display is as common as a normal LED sketch. In case of using common anode module, in digitalWrite (), all 0’s should be mentioned as 1 and all 1’s should be mentioned as o.

Circuit Diagram Arduino UNO - 7 Segment - COMMON CATHODE

//Sketch - 7 Segment - COMMON CATHODE int a= 2; int b= 3; int c= 4; int d= 5; int e= 6; int f= 7; int g= 8; int t = 500; void setup() { pinMode (a, OUTPUT); pinMode (b, OUTPUT); pinMode (c, OUTPUT); pinMode (d, OUTPUT); pinMode (e, OUTPUT); pinMode (f, OUTPUT); pinMode (g, OUTPUT); } void loop() { digitalWrite (a,1); digitalWrite (b,1); digitalWrite (c,1); digitalWrite (d,1); digitalWrite (e,1); digitalWrite (f,1); digitalWrite (g,0); delay(t); //1 digitalWrite (a,0); digitalWrite (b,1); digitalWrite (c,1); digitalWrite (d,0); digitalWrite (e,0); digitalWrite (f,0); digitalWrite (g,0); delay(t); //2 digitalWrite (a,1); digitalWrite (b,1); digitalWrite (c,0); digitalWrite (d,1); digitalWrite (e,1); digitalWrite (f,0); digitalWrite (g,1); delay(t); //3 digitalWrite (a,1); digitalWrite (b,1); digitalWrite (c,1); digitalWrite (d,1); digitalWrite (e,0); digitalWrite (f,0); digitalWrite (g,1); delay(t); //4 digitalWrite (a,0); digitalWrite (b,1); digitalWrite (c,1); digitalWrite (d,0); digitalWrite (e,0); digitalWrite (f,1); digitalWrite (g,1); delay(t); //5 digitalWrite (a,1); digitalWrite (b,0); digitalWrite (c,1); digitalWrite (d,1); digitalWrite (e,0); digitalWrite (f,1); digitalWrite (g,1); delay(t);

//6 digitalWrite (a,1); digitalWrite (b,0); digitalWrite (c,1); digitalWrite (d,1); digitalWrite (e,1); digitalWrite (f,1); digitalWrite (g,1); delay(t); //7 digitalWrite (a,1); digitalWrite (b,1); digitalWrite (c,1); digitalWrite (d,0); digitalWrite (e,0); digitalWrite (f,0); digitalWrite (g,0); delay(t); //8 digitalWrite (a,1); digitalWrite (b,1); digitalWrite (c,1); digitalWrite (d,1); digitalWrite (e,1); digitalWrite (f,1); digitalWrite (g,1); delay(t); //9 digitalWrite (a,1); digitalWrite (b,1); digitalWrite (c,1); digitalWrite (d,1); digitalWrite (e,0); digitalWrite (f,1); digitalWrite (g,1); delay(t); } Observed Output 0-9 Numbers Displayed in 7 Segment LED

Circuit Diagram Arduino UNO - 7 Segment - COMMON ANODE

//Sketch - 7 Segment - COMMON ANODE int a= 2; int b= 3; int c= 4; int d= 5; int e= 6; int f= 7; int g= 8; int t = 500; void setup() { pinMode (a, OUTPUT); pinMode (b, OUTPUT); pinMode (c, OUTPUT); pinMode (d, OUTPUT); pinMode (e, OUTPUT); pinMode (f, OUTPUT); pinMode (g, OUTPUT); } void loop() { digitalWrite ( a,0); digitalWrite ( b,0); digitalWrite ( c,0); digitalWrite ( d,0); digitalWrite ( e,0); digitalWrite ( f,0); digitalWrite (g,1); delay(t); //1 digitalWrite (a,1); digitalWrite ( b,0); digitalWrite ( c,0); digitalWrite (d,1); digitalWrite (e,1); digitalWrite (f,1); digitalWrite (g,1); delay(t); //2 digitalWrite (a,0); digitalWrite (b,0); digitalWrite (c,1); digitalWrite (d,0); digitalWrite (e,0); digitalWrite (f,1); digitalWrite (g,0); delay(t); //3 digitalWrite (a,0); digitalWrite (b,0); digitalWrite (c,0); digitalWrite (d,0); digitalWrite (e,1); digitalWrite (f,1); digitalWrite (g,0); delay(t); //4 digitalWrite (a,1); digitalWrite (b,0); digitalWrite (c,0); digitalWrite (d,1); digitalWrite (e,1); digitalWrite (f,0); digitalWrite (g,0); delay(t); //5 digitalWrite (a,0); digitalWrite (b,1); digitalWrite (c,0); digitalWrite (d,0); digitalWrite (e,1); digitalWrite (f,0); digitalWrite (g,0); delay(t);

//6 digitalWrite ( a,0); digitalWrite (b,1); digitalWrite ( c,0); digitalWrite ( d,0); digitalWrite ( e,0); digitalWrite ( f,0); digitalWrite ( g,0); delay(t); //7 digitalWrite ( a,0); digitalWrite ( b,0); digitalWrite ( c,0); digitalWrite (d,1); digitalWrite (e,1); digitalWrite (f,1); digitalWrite (g,1); delay(t); //8 digitalWrite ( a,0); digitalWrite ( b,0); digitalWrite ( c,0); digitalWrite ( d,0); digitalWrite ( e,0); digitalWrite ( f,0); digitalWrite ( g,0); delay(t); //9 digitalWrite ( a,0); digitalWrite ( b,0); digitalWrite ( c,0); digitalWrite ( d,0); digitalWrite (e,1); digitalWrite ( f,0); digitalWrite ( g,0); delay(t); } Observed Output 0-9 Numbers Displayed in T Segment LED

24. Write an arduino program to demonstrate button Circuit Diagram & Sketch Arduino UNO - Button // Sketch - Button #define BUTTON_PIN 4 void setup() { Serial.begin (9600); pinMode (BUTTON_PIN, INPUT); } void loop() { Serial.println ( digitalRead (BUTTON_PIN)); delay(100);} Observed Outputs (In Serial Monitor) Uneven values are printed. Sometimes 1 and sometimes 0, without the dependency on button press, which are called as floating values.

A. Understanding INPUT_PULLUP In pinMode (), along with INPUT & OUTPUT, we have third option INPUT_PULLUP. This option is the same as INPUT (you read data from the sensor), but in addition to that, an internal pull up resistor - between 20k and 50k Ohm - is enabled, to keep the signal HIGH by default. When we press the button, the value is always LOW, but when we release it it’s quite random: sometimes HIGH, sometimes LOW, and it moves a lot. We see this because the voltage for the button is floating between 0 and 5V. If the voltage is below a certain amount of V, the Arduino will read LOW. And if it is above a certain amount of V, the Arduino will read HIGH. As there is no internal or external voltage reference for the push button, the value will oscillate a lot in a random way. What we need to do is to “force” the default state (button not pushed) to be close to HIGH or LOW, which will make it quite stable. Then, when we press the button the state will simply go to the opposite of the default state. When you set the mode to INPUT_PULLUP, an internal resistor - inside the Arduino board - will be set between the digital pin 4 and VCC (5V). This resistor - value estimated between 20k and 50k Ohm - will make sure the state stays HIGH. When you press the button, the states becomes LOW.

Circuit Diagram Arduino UNO - Button with INPUT_PULLUP

// Sketch - Button with INPUT_PULLUP #define BUTTON_PIN 4 void setup() { Serial.begin (9600); pinMode (BUTTON_PIN, INPUT_PULLUP); } void loop() { Serial.println ( digitalRead (BUTTON_PIN)); delay(100);} Observed Outputs (In Serial Monitor) 1 1 When button is not pressed When button is pressed

//Sketch - Button (Input Pullup Resistor) with LED #define BUTTON_PIN 4 #define LED 9 void setup() { Serial.begin (9600); pinMode (BUTTON_PIN, INPUT_PULLUP); pinMode (LED, OUTPUT); } void loop() { Serial.println ( digitalRead (BUTTON_PIN)); delay(1000); if( digitalRead (BUTTON_PIN)==0) digitalWrite (LED, HIGH); else digitalWrite (LED, LOW); }

Circuit Diagram Arduino UNO - Button (Input Pullup Resistor) with LED 01 LED ON LED OFF Observed Outputs (In Serial Monitor)

25. Write an arduino program to demonstrate switch // Sketch - Toggle Switch #define TOGGLESWITCH 4 void setup() { Serial.begin (9600); pinMode (TOGGLESWITCH, INPUT_PULLUP); } void loop() { Serial.println ( digitalRead (TOGGLESWITCH)); delay(100); } A toggle switch is simply a push button switch with memory. The difference between a toggle switch and a push button switch is that the toggle switch can remain either high or low, whereas a push button input is momentarily connected when pushed. A spring pushes the button back when you release it. Arduino sketch remains same for button and toggle switch and even INPUT_PULLUP can also be used as same in button.

Observed Outputs (In Serial Monitor) 01 Switch Position ON Switch Position CENTER Circuit Diagram Arduino UNO - Toggle Switch

Circuit Diagram Arduino UNO - Toggle Switch as Two Buttons

// Sketch - Toggle Switch as Two Buttons #define TOGGLELEFT 4 #define TOGGLERIGHT 5 #define LEDRED 9 #define LEDGREEN 13 void setup() { pinMode (TOGGLELEFT, INPUT_PULLUP); pinMode (LEDRED, OUTPUT); pinMode (TOGGLERIGHT, INPUT_PULLUP); pinMode (LEDGREEN, OUTPUT); } void loop() { //for toggle switch left direction if( digitalRead (TOGGLELEFT)==0) digitalWrite (LEDRED, HIGH); else digitalWrite (LEDRED, LOW);

//for toggle switch right direction if( digitalRead ( TOGGLERIGHT)==0) digitalWrite (LEDGREEN, HIGH); else digitalWrite (LEDGREEN, LOW); } Observed Outputs (In Serial Monitor) When toggle switch is positioned left, RED LED is switched on. When toggle switch is positioned right, GREEN LED is switched on.

TASK 7 26. Write an arduino program to demonstrate interrupts. 27. Write an arduino program to demonstrate UART communication protocol

26. Write an arduino program to demonstrate interrupts Interrupts stop the current work of Arduino such that some other work can be done. Interrupt is a signal emitted by hardware or software when a process or an event needs immediate attention. It alerts the processor to a high priority process requiring interruption of the current working process. There are software and Hardware interrupts : Hardware Interrupts - These occur in response to an external event, like a pin going high or low (may be a action of a simple push button). Software Interrupts - These occur in response to a software instruction, that is writing in the program. Most Arduino designs have two hardware interrupts (referred to as "interrupt0" and "interrupt1") hard-wired to digital I/O pins 2 and 3, respectively. ISR

INTERRUPT PIN DETAILS ON VARIOUS ARDUINO MODELS Interrupt Service Routine (ISR) Interrupt Service Routine (ISR) or an Interrupt handler is an event that has small set of instructions in it. When an external interrupt occurs, the processor first executes these code that is present in ISR and returns back to state where it left the normal execution. ISR Declaration Syntax attachInterrupt (digitalPinToInterrupt(pin), ISR, MODE); digitalPinToInterrupt (pin): Pin Number (INT0/ INT1 - Pin 2/Pin 3 in Arduino UNO) ISR: It is a function that is called when an external interrupt is done. Mode: Type of transition to trigger on, e.g. FALLING, RISING, CHANGE. RISING: To trigger an interrupt when the pin transits from LOW to HIGH. FALLING: To trigger an interrupt when the pin transits from HIGH to LOW. CHANGE: To trigger an interrupt when the pin transits from LOW to HIGH or HIGH to LOW (i.e., when the pin state changes ).

//Sketch - ISR #define LED_PIN 13 #define BUTTON_PIN 3 volatile byte ledState = HIGH; void setup() { pinMode (LED_PIN, OUTPUT); pinMode (BUTTON_PIN, INPUT_PULLUP); attachInterrupt ( digitalPinToInterrupt (BUTTON_PIN), blinkLed , CHANGE); } void loop() { // nothing here! } void blinkLed () { ledState = ! ledState ; digitalWrite (LED_PIN, ledState ); }

Circuit Diagram Arduino UNO - ISR Observed Outputs (In Serial Monitor) When button is pressed, the control is going to blinkled () and LED blink can be observed accordingly.

2 7 . Write an arduino program to demonstrate UART Communication Protocol Project is about controlling the built-in LED of an Arduino remotely via UART . A push-button wired to the first Uno board will control the built-in LED of the second Uno board and vice versa. For this project, both boards will have identical sketches . Please remember to disconnect the wires connected to TX0 and RX0 pins before uploading the sketch. After uploading successfully, reconnect the wires on TX0 and RX0 pins . Circuit Diagram Arduino UNO - UART

//Sketch - UART DEMO WITH TWO Arduino UNO boards void setup() { pinMode (8, INPUT_PULLUP); pinMode (13, OUTPUT); digitalWrite (13, LOW); Serial.begin (9600); } void loop() { if ( Serial.available ()) { char data_rcvd = Serial.read (); if ( data_rcvd == '1') digitalWrite (13, HIGH); if ( data_rcvd == '0') digitalWrite (13, LOW); } if ( digitalRead (8) == HIGH) Serial.write ('0'); else Serial.write ('1'); }

Observed Outputs (In Serial Monitor) When the button on one board is pressed, we can see the LED on other board acts as per the defined button press actions.

TASK 8 28. Write an arduino program to demonstrate I2C communication protocol.

TASK 9 29. Write an arduino program to demonstrate SPI communication protocol.

TASK 10 30. Write an arduino program for interfacing with potentiometer. 31. Write an arduino program for interfacing with temperature sensor. 32. Write an arduino program for interfacing with PIR sensor.

30. Write an arduino program for interfacing with potentiometer. A potentiometer (also known as a pot or potmeter ) is defined as a 3 terminal variable resistor in which the resistance is manually varied to control the flow of electric current. You have probably used one before by adjusting the volume on your stereo or using a light dimmer . A potentiometer is a simple mechanical device that comes in many different forms . It provides a variable amount of resistance that changes as you manipulate it physically . The typical potentiometer will have 3 pins, two power supply pins (+5V and GND), and one pin that connects to an analog pin on your Arduino to read the value output. POTENTIOMETER SYMBOL OF POTENTIOMETER

Potentiometers have a range of resistance . They can be attuned from zero ohms to whatever maximum resistance that is specific to it. For example, a potentiometer of 10 kΩ can be adjusted from 0 Ω to its maximum of 10 kΩ . By turning the shaft of the potentiometer , we change the amount of resistance on either side of the wiper which is connected to the center pin of the potentiometer . This changes the relative "closeness" of that pin to 5 volts and ground, giving us a different analog input. This changes the relative "closeness" of that pin to 5 volts and ground, giving us a different analog input. When the shaft is turned all the way in one direction, there are 0 volts going to the pin, and we read 0 . When the shaft is turned all the way in the other direction, there are 5 volts going to the pin and we read 1023 . In between, analogRead () returns a number between 0 and 1023 that is proportional to the amount of voltage being applied to the pin. Below scenario shows you how to read an analog input on analog pin 0, convert the values from analogRead () into voltage, and print it out to the serial monitor of the Arduino Software (IDE). Connect the three wires from the potentiometer to your board. The first goes to ground from one of the outer pins of the potentiometer. The second goes to 5 volts from the other outer pin of the potentiometer. The third goes from the middle pin of the potentiometer to analog input 0.

Circuit Diagram Arduino UNO - Interfacing Potentiometer

// Sketch - Interfacing Potentiometer void setup() { Serial.begin (9600); } void loop() { // read the input on analog pin 0 int sensorValue = analogRead (A0); // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V) float voltage = sensorValue * (5.0 / 1023.0); // print out the value you read: Serial.println (voltage); } Observed Output (In Serial Monitor) Variable voltage values are seen with respective turning movement of potentiometer.

31. Write an arduino program for interfacing with temperature sensor. LM35 is a temperature sensor which can measure the temperature in the range of -55°C to 150°C . It is a 3-terminal device that provides analog voltage proportional to the temperature . The sensitivity of LM35 is 10 mV/degree Celsius (Example: 250 mV means 25°C). As temperature increases, output voltage also increases . The output analog voltage can be converted to digital form using ADC so that a microcontroller can process it. As the LM35 sensor provides an output of 10mV per degree Celsius, so the code first reads the ADC value from the sensor , then converts it to an equivalent voltage , and finally converts that voltage value to a temperature value in degrees Celsius. FLAT EDGE PINOUT OF LM35 TEMPERATURE SENSOR

Circuit Diagram Arduino UNO - Interfacing LM 35 Sensor

// Sketch - Interfacing LM 35 Sensor const int lm35_pin = A1; /* LM35 O/P pin */ void setup() { Serial.begin (9600); } void loop() { int temp_adc_val ; float temp_val ; temp_adc_val = analogRead (lm35_pin); /* Read raw value from sensor */ temp_val = ( temp_adc_val * 4.88); /* Convert raw value to equivalent voltage */ temp_val = ( temp_val /10); /* Convert voltage to temperature @ 10mv/°C */ Serial.print ("Temperature = "); Serial.print ( temp_val ); Serial.print (" Degree Celsius\n"); delay(1000); }

Observed Output (In Serial Monitor)

32. Write an arduino program for interfacing with PIR sensor. The term PIR is the short form of the Passive InfraRed . The term “passive "indicates that the sensor does not actively take part in the process , which means, it does not emit the referred IR signals itself, rather passively detects the infrared radiations coming from the human body in the surrounding area. The detected radiations are converted into an electrical charge , which is proportional to the detected level of the radiation. Then this charge is further improved by a built in FET (field-effect transistor (FET) is a type of transistor commonly used for weak-signal amplification) and the amplified signal is further fed to the output pin of the device which is connected to an external circuit for further triggering of operations. Fresnel Lense

Understanding PIR Sensor Calibration Sensitivity Adjustment Time Delay Adjustment The knob on the right controls sensitivity . Turn it clockwise to decrease sensitivity. Decreased sensitivity means that the device will trigger (i.e. report movement) only when said movement is prolonged. Sensitivity can be adjusted over a range of approximately 3 meters to 7 meters (9 to 21 feet). However the topology of your room can affect the actual range you get. The knob on the left sets how long the output will remain HIGH after motion is detected. It can be adjusted from 5 seconds to about 5 minutes.

Working of PIR Sensor The passive infrared (PIR) sensor itself has two slots (two pyroelectric sensors) in it , each slot is made of a special material that is sensitive to IR . The lens used here is not really doing much and so we see that the two slots can 'see' out past some distance (basically the sensitivity of the sensor). When the sensor is idle, both slots detect the same amount of IR , the ambient amount radiated from the room or walls or outdoors. When a warm body like a human or animal passes by, it first intercepts one half of the PIR sensor, which causes a positive differential change between the two halves. When the warm body leaves the sensing area, the reverse happens , whereby the sensor generates a negative differential change. These change pulses are what is detected.

The IR sensor itself is housed in a thermetically sealed metal can to improve noise/temperature/humidity immunity . There is a window made of IR-transmissive material (typically coated silicon since that is very easy to come by) that protects the sensing element. Behind the window are the two balanced sensors. The sensor module also consists of a specifically designed cover called Fresnel lens that helps focus the infrared signals onto the pyroelectric sensor . However, remember that we actually have two sensors, and more importantly we don't want two really big sensing-area rectangles, but rather a scattering of multiple small areas. So what we do is split up the lens into multiple section , each section of which is a Fresnel lens.

FRESNEL LENSE FRONT AND REAR VIEW

Circuit Diagram Arduino UNO - Interfacing PIR Sensor

// Sketch - Interfacing PIR Sensor const int PIR_SENSOR_OUTPUT_PIN = 4; /* PIR sensor O/P pin */ int warm_up ; void setup() { pinMode (PIR_SENSOR_OUTPUT_PIN, INPUT); Serial.begin (9600); delay(20000); /* Power On Warm Up Delay */ } void loop() { int sensor_output ; sensor_output = digitalRead (PIR_SENSOR_OUTPUT_PIN); if( sensor_output == LOW ) { if( warm_up == 1 ) { Serial.print ("Warming Up\n\n"); warm_up = 0; delay(2000);}

Serial.print ("No object in sight\n\n"); delay(1000);} else{ Serial.print ("Object detected\n\n"); warm_up = 1; delay(1000);}} Observed Output (In Serial Monitor)

TASK 11 33. Write an arduino program for interfacing with infrared sensor. 34. Write an arduino program for interfacing with ultrasonic sensor. 35. Write an arduino program for interfacing with accelerometer

33. Write anAarduino sketch for interfacing with Infrared Sensor An infrared (IR) sensor is a proximity sensor, or a ‘nearness’ sensor that senses whether there is an object near it or not . It is also used to measure distance . Note that, Infrared is the light out of our visible spectrum, so we can not see it. The white LED here is an IR LED which works as the transmitter and the component next to the IR LED is a photodiode that works as the receiver in the IR sensor. The IR transmitter continuously emits the IR light and the IR receiver keeps on checking for the reflected light . If the light gets reflected back by hitting any object in front it, the IR receiver receives this light. This way the object is detected in the case of the IR sensor. The blue knob is a potentiometer . You can control the range i.e. from how far you want to detect the object by changing the value of the potentiometer. An IR sensor has two small LED indicators - one for Power , which is ON the entire time the sensor is ON; the other is the Signal LED which detects the object. The signal LED has two states or situations: ON (Active) when it detects an object and OFF (Inactive) when it doesn’t detect any object They are widely used in various applications such as remote control devices , security systems , obstacle detection , and industrial automation .

Understanding Pinout & Components of IR Sensor NOTE There are two types of IR sensors are available and they are, Active Infrared Sensor & Passive Infrared Sensor. Active infrared sensors consist of two elements: infrared source and infrared detector. Passive infrared sensors are basically Infrared detectors only.

Object Detection using IR Sensor When the IR transmitter emits radiation, it reaches the object and some of the radiation reflects back to the IR receiver. Based on the intensity of the reception by the IR receiver, the output of the sensor is defined.

Circuit Diagram Arduino UNO - Interfacing Infrared Sensor (Object Detection)

// Sketch - Interfacing IR Sensor (Object Detection) int IRSensor = 9; // connect IR sensor module to Arduino pin D9 int LED = 13; // connect LED to Arduino pin 13 void setup(){ Serial.begin (115200); // Init Serial at 115200 Baud Rate. Serial.println ("Serial Working"); // Test to check if serial is working or not pinMode ( IRSensor , INPUT); // IR Sensor pin INPUT pinMode (LED, OUTPUT); // LED Pin Output } void loop(){ int sensorStatus = digitalRead ( IRSensor ); // Set the GPIO as Input if ( sensorStatus == 1) // Check if the pin high or not { // if the pin is high turn off the onboard Led digitalWrite (LED, LOW); // LED LOW Serial.println (“Object Detected!"); } else {

//else turn on the onboard LED digitalWrite (LED, HIGH); // LED High Serial.println (“No Object"); } } Observed Output (In Serial Monitor) Status printed as per the object detection takes place.

34. Write an arduino program for interfacing with Ultrasonic Sensor The Ultrasonic Sensor (HC-SR04) is an affordable and easy to use distance measuring sensor which has a range from 2cm to 400cm (about an inch to 13 feet) . The sensor is composed of two ultrasonic transducers. One is transmitter which outputs ultrasonic sound pulses and the other is receiver which listens for reflected waves . When the power supply is given to this module, transmitter transmits the sound waves that travels through the air to hit the necessary object. These waves strike and come back from the object, then collects by the receiver module . Here the amount of time taken to transmit and receive the waves will decide the distance between the sensor and an object . Here both the distance as well as time has taken is directly proportional because the time taken for more distance is high. The HC-SR04 Ultrasonic sensor comes with four pins namely Vcc pin , Trigger pin , Echo pin , & Ground pin . WORKING

VCC and GND go to 5V and GND pins on the Arduino, and the Trig and Echo go to any digital Arduino pin . Using the Trig pin we send the ultrasound wave from the transmitter, and with the Echo pin we listen for the reflected signal. In order to generate the ultrasound we need to set the Trig pin on a High State for 10 µs . That will send out an 8 cycle ultrasonic burst which will travel at the speed of sound (which is 340m/s and this value is fixed for this sensor) . The Echo pins goes high right away after that 8 cycle ultrasonic burst is sent , and it starts listening or waiting for that wave to be reflected from an object . If we receive a reflected pulse, the Echo pin will go down . According to the amount of time the Echo pin was HIGH, we can determine the distance the sound wave traveled , thus the distance from the sensor to the object. If there is no object or reflected pulse, the Echo pin will time-out after 38ms and get back to low state. Calculating Distance We are using the following basic formula for calculating distance: Distance = Speed x Time We actually know both the speed and the time values. The time is the amount of time the Echo pin was HIGH , and the speed is the speed of sound which is 340m/s . There’s one additional step we need to do, and that’s divide the end result by 2 . and that’s because we are measuring the duration the sound wave needs to travel to the object and bounce back.

Circuit Diagram Arduino UNO - Interfacing Ultrasonic Sensor

// Sketch - Interfacing Ultrasonic Sensor // defines pins numbers const int trigPin = 9; const int echoPin = 10; // defines variables long duration; int distance; void setup() { pinMode ( trigPin , OUTPUT); // Sets the trigPin as an Output pinMode ( echoPin , INPUT); // Sets the echoPin as an Input Serial.begin (9600); // Starts the serial communication } void loop() { // Clears the trigPin digitalWrite ( trigPin , LOW); delayMicroseconds (2);

// Sets the trigPin on HIGH state for 10 micro seconds digitalWrite ( trigPin , HIGH); delayMicroseconds (10); digitalWrite ( trigPin , LOW); // Sound wave travel time from echo in microseconds duration = pulseIn ( echoPin , HIGH); // Calculating the distance distance = duration * 0.034 / 2; // Prints the distance in the Serial Monitor Serial.print ("Distance: "); Serial.println (distance); } Observed Output Distance of the object successfully calculated and got printed in Serial Monitor.

35. Write an arduino program for interfacing with accelerometer Have you ever wondered how your smartphone knows which way is up? It’s one of the most innovative features of today’s smartphones. They all have a tiny device called an accelerometer built into the circuitry that detects when you tilt the device from side to side . That’s how your smartphone knows when to switch from portrait to landscape mode. Accelerometers are widely used in low-power , low-cost motion and tilt sensing applications such as mobile devices, gaming systems, disk drive protection, image stabilization, and sports and health devices. Y+ Y- ADXL345 can measure static and dynamic accelerations and suitable for mobile applications . Also, these sensors are laboratory calibrated and don’t require any further calibrations . Here we will use two Adafruit libraries for the ADXL345 sensor to interface it with Arduino Uno. To understand how accelerometers work, imagine a ball inside a 3D cube, as shown in the figure;

If we suddenly move the box to the left with acceleration 1g (a single G-force 1g is equivalent to gravitational acceleration 9.8 m/s2) , the ball will undoubtedly hit the wall X. If we measure the force the ball exerts on wall X, we can obtain an output value of 1g along the X axis, as shown in right side figure; Let’s see what happens when we place that cube on Earth. The ball will simply fall on the wall Z, exerting a force of 1g as shown in left side figure. In this case, the box isn’t moving, but we still get a 1g reading on the Z axis. This is because gravity (which is actually a form of acceleration) is pulling the ball downward with a force of 1g. Y+ Y- Y+ Y-

While this model does not exactly represent how a real-world accelerometer sensor is built, it is often useful in understanding why an accelerometer’s output signal is typically specified in ±g, or why an accelerometer reads 1g in the z-axis at rest, or what accelerometer readings you can expect at different orientations . In the real world, accelerometers are based on Micro-Electro-Mechanical Systems (MEMS fabrication technology). So, let’s find out how a MEMS accelerometer works.

This structure is suspended by polysilicon springs. It allows the structure to deflect when accelerated along the X, Y, and/or Z axes. As a result of deflection, the capacitance between fixed plates and plates attached to the suspended structure changes. This change in capacitance is proportional to the acceleration along that axis. The sensor processes this change in capacitance and converts it into an analog output voltage. There are many types of MEMS accelerometer sensors available in the market. They can be classified on the basis of precision, power consumption, and interfacing. All these sensors are portable and can be fitted in any kind of device like wearables. These sensors measure acceleration in 3-axis ( x,y,z ). Some widely used MEMS accelerometer Sensors are: ADXL335, ADXL345 and ADXL356. ADXL 345 is popular among all. ADXL 345 IC Voltage Regulator IC

ADXL 345 WORKING WITH ARDUINO UNO The ADXL335 operates on 1.8V to 3.6VDC (typically 3.3V). However, the on-board 3.3V regulator makes it ideal for interfacing with 5V microcontrollers like the Arduino. The sensor consumes only 350μA of current during normal operation. The ADXL335 has a full sensing range of ±3g. Meaning the maximum amount of acceleration that the ADXL335 can accurately measure and represent as an output is ±3g. -3g is at 0v, and +3g is at 3.3V, with full scaling in between. We need to install two libraries in Arduino IDE for working with the ADXL345 Sensor; Adafruit ADXL345 Adafruit Unified sensor To download the above libraries, open Arduino IDE and go to Sketch -> Include Library -> Manage Libraries. Search for Adafruit ADXL345 and install it. Similarly, search for Adafruit Unified sensor and install. Now, we are ready to write the code. Example code can be found in Files -> Example -> Adafruit ADXL345 -> sensortest .

Circuit Diagram Arduino UNO - Interfacing ADXL 345 Accelerometer Sensor

// Sketch - Interfacing Interfacing ADXL 345 Accelerometer Sensor #include < Wire.h > #include < Adafruit_Sensor.h > #include <Adafruit_ADXL345_U.h> Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(); void setup(void) { Serial.begin (9600); if(! accel.begin ()) { Serial.println ("No valid sensor found"); while(1); } } void loop(void) { sensors_event_t event; accel.getEvent (&event);

Serial.print ("X: "); Serial.print ( event.acceleration.x ); Serial.print (" "); Serial.print ("Y: "); Serial.print ( event.acceleration.y ); Serial.print (" "); Serial.print ("Z: "); Serial.print ( event.acceleration.z ); Serial.print (" "); Serial.println ("m/s^2 "); delay(500); } Observed Output