Lesson Smart Security Applications with C - Internet of Things - ثاني ثانوي
Part 1
1. IoT Fundamentals
2. The IoT in Our Lives
3. Building IoT applications with Arduino
4. Building an IoT cloud application
Part 2
5. IoT Advanced Applications
6. ++IoT Programming With C
7. IoT messaging
8. IoT Wireless Sensor Network Simulation
206 6. IoT Programming with C++ In this unit, you will learn about smart security applications. You will also learn the fundamentals of the C++ programming language for the Arduino microcontroller and how to transition from codeblocks to C++ In Tinkercad Circuits. Finally, you will build a smart security project with an Arduino microcontroller and program it with C++. Learning Objectives In this unit, you will learn to: > Identify the benefits and the risks of an IoT security system. > Name some common loT devices used in smart security systems. > Recognize the common data types in C++. > Use operators in C++. > Use conditional statements in C++. > Use loops in C++. > Create a function in C+++. > Convert the Tinkercad blocks into C++ commands. > Program an Arduino smart security system with C++. Tools > Autodesk Tinkercad Circuits
Lesson 1 Smart Security Applications with C++ Link to dangal www.len.edusa Smart Security A smart security system is a way or a process of securing something using a network of cooperating parts and tools. IoT systems can handle inspections in and around your property and keep track of who has access to gates and doors with smart locks if they are installed. For example, smart doorbells can recognize and interact with visitors before unlocking the front door. Motion-activated high-definition cameras are integrated into these gadgets. To secure your home, smart security systems warn you of any anomalies and can set off an alarm or even contact the police. Benefits There are numerous reasons for implementing an intelligent home security system. IoT enables remote monitoring and management of your home via a mobile application. Nowadays, smart security devices employ Al to detect environmental changes and warn users. In response to the alert, the devices initiate a specified action. People invest in smart home security systems to make their residences more secure. These cutting-edge technologies provide you with keyless entry to your home and give you real-time security updates. Risks However, the lack of legislation surrounding the usage and security of IoT devices poses a serious threat to the deployment of loT in a smart home. In the lack of worldwide security standards, privacy and data security risks arise while using loT devices. Every Internet of Things gadget in your house collects data. If you want to keep your lifestyle private, you must safeguard every system that gathers and retains your personal information. وزارة التعليم Figure 1 using a phone open Sutumunun affice building 177-1860
208 Keeping the risks in mind, let's explore some of the most common loT-enabled devices used in smart security systems. Table 6,1: Common loT-enabled devices Devices Uses in smart security systems Smart locks and alarms Smart locks Improve the security of your house and allow you to remotely operate the front door. You may set restrictions to enable visitors' entry at certain periods of time. Some smart locks provide more advanced features such as fingerprint, face-scan, or even eye scan authentication. Smart cameras A home security system is incomplete without the integration of smart cameras Cameras serve as the digital eyes of your hame allowing you to watch any activity inside and outside in real-time There are several intelligent camera options available, including Wireless IP cameras that can be monitored from any location with an internet connection. Surveillance video of the regions around the entrance gales may be captured by door or gate cameras. Fire and smoke sensors It is crucial to install fire and smoke detectors to get notified Instantly when there is a hazardous situation in your residence. Smart homes are often built with carbon monoxide detectors that provide alerts when they detect dangerously high amounts of gas. They may also activate the sprinkler system or notify the fire department to ensure that the fire does not spread uncentrolled and cause property loss or injuries. Γ Rotion sensors رارت التعليم 2171-155 Motion detectors are a vital component of a smart security system Vibrations and inputs are recorded and analyzed in both two and three dimensions by these systems, which then can indicate any Irregular motion. They may activate alarms to notify users of activities inside or in the local vicinity of the house.
C++ Language Achieving robust security is hard and thus we need powerful languages such as C++ to program interfaces. C++ is a high level compiled programming language that has many object-oriented and functional features on top of many low-level memory-handling capabilities. Its main characteristics are performance speed and efficiency. C++ was designed as an extension of the C programming language. Basic Data Types In contrast to other programming languages, in C++ you need to specify the type of a variable before using it. Variables need to have a type that indicates what kind of data each variable holds. The C++ program needs this information to know how much memory is needed to be allocated for these data. Table 6.2: The most common data types in C++ You can alter a type by using a type modifier e.g. long int. The possible combinations are: Type Identifier Example Integers (int) 5, 4 char int double signed Fluaong point numbers (float or double) unsigned 3.14 -7.5 short long Characters (char) Bocleans (bool) bool flag = true; The programmer can also define their own types based on their needs. When creating a variable there are some naming rules that you need to follow. Valid names: • Can only have alphabets (A-Z, a-z), numbers (0-9), and the underscore (_). ■Cannot begin with a number. ■ Cannot be a keyword. For example, int is a keyword that is used to denote integers. Variables can be declared with or without being initialized. Arrays A very common data structure in C++ is the array. An array is essentially a variable that can hold multiple values of the same type. The syntax for declaring an array is: datatype arrayName[arraySize]; أوزارة التعليم matrix type matrix name matrix size 2003-14 209
210 After declaration, you cannot change the array's type or size. You can access its elements by using their indices. For example, if you want to store 10 integer values you can create an array in which you will store the values. First, you must declare the array's type and size: int values[10]; where int is the type of the elements stored in the array, the array's name is "values" and its size is 10. To fill it with values the command is: values [10] {0,1,2,3,4,5,6,7,8,9); To access any of its elements, you just need its index. So, the command: int a values[3]; declares a variable called a, which is of integer type and its value is the 4th element of the values array (indexing in C++ starts from 0). Although you can have arrays of more than one dimension, the most common types are one-dimensional or two-dimensional. To create a 2d array, you need to declare the size of each dimension. For example: char keys[4][2]; declares an array with 4 rows and 2 columns which can store values of type char. To fill the array with your values you work as in the 1d arrays; keys[4][2] = {{1,2}, (3,4}, (5,6}, {7,8} 2173-1985 Here you need a pair of values for each row.
Basic Operators in C++ The basic types of operators are arithmetic, assignment, relational and logical. Table 6.3: Arithmetic operators Operator Operation Additon Subtraction Multiplicatien Table 6.4: Assignment operators Operator = 4= -= Example Equivalent to a=b: a = b₁ a = b; a=a+b a-a-b; a-b Division Modulo Operation (Remainder after division) *= a = by a = a b /= a/= b: a = a/b; Ply a = b a=ab In integer (int) arithmetic, "/" is used to calculate the quotient of the division and "%" is used for the remainder. eg. 5/2=2,5%2=1 In floating-point (float, double) arithmetic, only "/"" is used for the quotient. e.g. 5.0/2.0-2.5 Table 6.5: Relational operators Operator Meaning Is Equal to |= > >= <= Example 3 = 5 gives us false Not Equato Greater than Less than Greater Than or Equal to Less Than or equal to 3|= gives us true 3>> gives us false 3<5 gives us true 3>=5 gives us false 3 <= 5 gives in true Table 6.6: Logical operators Operator وزارة التعليم 2173-1455 Meaning pression! && expression2 expression expression2 !expression Logical AND Example True only if all operands are true. Logical DR frue if at least one of the operands is true Logical NOT True only if the operands is false. 211
Comments in C++ Another basic feature every programming language supports is comments. These comments are ignored by the compiler and are used to improve the readability of the code, making it easier for programmers or code reviewers to understand the functionality of the code. There are two ways to add a comment in C++ depending on whether you want the comment to span multiple lines or not. Use // for a single line of comment this is a comm Inactive code int y = 10; cout <<y; Use /* to start a block comment and */ to end it. Block comments are also used to make a part of the code inactive while testing the functionality of the program. For example, in the following code, the if statement will be skipped by the compiler. lcd.clear(); lcd.setCursor(0, 0); lcd.print("Enter password: "); bool correctPass = true; char buttonPressed; Y Index = 4: bill tonPressed = keypad.waitForKevil; LF(password index) (= buttonPresset) I curres = False, (1, 1); lcd.print(buttonPressed); وزارة التعليم 2173-1465 212 Inactive code
Printing in C++ To print a variable x in C++ use the following command cout << x; Conditional Statements in C++ To execute certain blocks of code depending on whether a condition is true, you can use three types of conditionals: ⚫ if statements ⚫ if... else statements ■ if...else if...else statements it statement This type of if statement is used when you want to execute a block of code in case a condition is met. The syntax of a simple if statement in C++ is: if (condition) { // body of if statement } fulse [YUB Candidon Modu Figure 62 if statement (lowchart First, the condition in parentheses is evaluated and if its value is true then the code inside the {} is executed. If the condition is false the code inside the {} is skipped. How if statement works: Condition is true Condition is false int number = 5; if (number > 0) { int number 5; if (number <0) { // code a fode after if التعليم JI73-1485 // code after if 213
if...else statement In this type of if...else statement, either the code block inside the if () will be executed and then the code inside else {} is skipped or the if () is skipped then the block of code inside the else [} will be executed. The syntax of an if...else statement is if (condition) { // block of code 1 if condition is true else // block of code 2 if condition is false false trae Condition 11 code 2 //cade! Elgun fel statement flowchart First, the condition in parentheses is evaluated and if its value is true then the code inside the if {} is executed. If the condition is false, the code inside the else { is executed. How if...else statement works: Condition is true Condition is false int number = 5; int number 5; if (number > 0) { W code Excented if (number 0) { Skippud // code } else { else { Shipport Executed // code // code // code after if...else وزارة التعليم J173-1445 214 // code after if...else
if...else if...else statement The last type of conditional if...else if...else is used when you need to check more than one condition or when you need 3 or more blocks of code to be executed depending on some conditions. The syntax of an if.. else if.. else statement is: if (condition1) { // code block 1 } else if (condition?) { //code block 2 Y else { 17 code black 3 } falve true Condition false true Condition 2 //cado 1 //code 3 وزارة التعليم J173-1445 // Lude 2 figure 6.4 if, else false statement flowclion 215
How if...else if...else statement works: if condition1 is True, code block 1 will be executed and the rest of the code blocks are skipped. 1st Condition is true If condition1 is False and condition2 is True, code block 2 will be executed and code block 3 is skipped. 2st Condition is true. int number = 2; int number 0; if (number) [ // code Execated if (number) { // code Skipped } else if (number == 0) { else if (number Skipped == 0) { Executed 11 code //code } } else ( else { Skipped // code // code } } // code after if // code after if If neither condition1 nor condition2 is True, code block 3 will be executed. All conditions are false. You can also nest an if statement inside the code block of another if statement. They don't have to be of the same type. For example: int number 0; if (number > 0) { Skipped outer if statement // code if (condition1) f } else if (number == 0) { Skipped // statements // code else [ pde after if الى التعليم 2173-1985 216 Executed } } inner if statement if (condition2) { // code after if
Loops In C++ you can use three types of loops: ⚫ "for" loop ■ "while" loop "do...while" loop var init false true Condition //cude "for" loop The syntax of a for loop is: for (variable initialization; condition; increment operation) { //loop statements; } Nigure 65: for looly flowchart cement op Where variable initialization is executed only once before the loop starts and it sets the starting values of the variables that are part of the condition. In this step, you can also declare and initialize a variable, usually the counter used for the loop iterations, by the condition. If the condition's value is True, the loop statements are executed and then the increment operation updates the values of the initialized variables. This continues until the condition's value changes to False. "while" loop The syntax of a while loop is: while (condition) { // loop statements; } true false Condition Il code Figure 6.6: while loop flowchart Where the loop statements are executed while the condition evaluates to True. When the condition becomes false the iteration stops and the loop statements are skipped. "do...while" loop The third iteration type, do...while, is a variation of the while loop and its syntax is: dp { statement execution; ;(ile (condition اسراره التعليم 2073-1485 false Il code Condition Figure 57 do...while loop flowchart true Its difference from the while loop is that in a do... while loop the condition is checked after the loop statements. This means that the code inside the body of the loop will be executed at least one time. The Iteration stops when the condition evaluates to False. 217
"break" and "continue" Statements When working with loops there are two very useful statements, "break" and "continue". They both work in every loop type. "break" Statement The break statement will terminate the loop in which it is encountered. for (init; condition; update) { //code block 1 if (condition to break) f break } // code block 2 // code after loop while (condition) { code block 1 if (condition to break) f break } // code block 2 // code after loop If the break statement is found inside the body of a nested loop, it terminates the inner loop. وزارة التعليم 173-1445 218 False Condition // code after loop true //code1 False break statement condition true // code 2 Figure 6.8 break statement flowchart
"continue" Statement The continue statement will skip the rest of the code inside the loop and go to the next iteration, for (init; condition; update) { //code block 1 if (condition to continue) { continue >while (condition) { // code block 1 if (condition to continue) { continue } } // code block 2 // code after loop If the continue statement is found inside the body of a nested loop it skips the current iteration of the Inner loop. } // code block 2 //code after loop false true Condition False // code after loop code 2 وزارة التعليم 13 - כקוע }) code 1 continue statement condition 219
220 Functions in C++ Quite often in programming, there are tasks that need to be executed many times. One solution would be to write the same lines of code every time these tasks need to be performed. A better solution is to group these lines of code and create a function that performs these tasks. In C++ there are many standard library functions, which are functions that are predefined and can be used by programmers. There is also the ability for programmers to define their own functions based on their needs. These are called user-defined functions. Every function can accept some variables as input parameters, execute some code which is enclosed in (), and to end the function there is a return statement, which returns a value. To create a function, you first need to declare it: returnType is the type of data the function returns to where it was called. functionName is the name of the function. returnType functionName (parameteri, parameter2,...) [ // function body (parameter, parameter) is the list of input parameters if there are any. An example of a very simple function that receives two integers and returns their sum is: // function declaration. int adding (int a, int b) { 5 ; a"」 return درارك التعليم 2173-1985
To use this function in your main code you call it by its name and pass as parameters two integers: int main() { int a=2; int b=5; int ci //calling the function and passing a, b as arguments adding(a,b); //cout will print the value of c с cout << c; return 0; Only in the main() function, the return statement is optional and can be omitted. As you can see, "main" is also a function that returns the value 0, hence its return type is int but accepts no input parameters in this case which is indicated by the empty parentheses (). "main" is a special kind of function in C++ where the main code of a program exists. The type, number and order of arguments passed to a function must match the type of the corresponding parameters in the function declaration. It is possible for a function to not return any value. In that case, the returnType will be "void". void disply Number () { // code } Setup() and Loop() Functions When writing code for Arduino in the Tinkercad platform, there are two functions that are called to execute the code of the circuit. These functions are called automatically when the program starts its execution unlike the rest of the functions that need to be called explicitly by your code. The first function that is executed is "void setup()". It is executed only once in the beginning, and it is responsible for setting up the various circuit parts. Things like setting the mode of each Arduino digital pin, establishing communication with the serial terminal and more are handled in the setup() function. After setup() has been executed, the function "void loop()" is called repeatedly as long as the system is powered. This is the function that performs the main functionality of the circuit. 23-1445 221
In general, you want to write the setting up code inside the body of void setup(), the main programming logic inside the body of void loop(), and any constant or function declarations outside the body of these two functions. Example of an Arduino C++ program. void setup() { int a = 10; int b = 20; setup() runs once to setup variables and objects void loop() { for (int i= 0; i<b; i++) { loop() runs repeatedly in the Arduino. a += 1; cout << a; 222 Classes, Objects, and Methods In the object-oriented programming, you basically want to perform all computations based on "objects". An object is the basic unit of object-oriented programming. Objects can have properties and can perform some basic actions. For example, a servo motor can be considered such an object. It has some properties (name, type) and can perform some basic actions such as reading from a digital pin, rotating its motor by a number of degrees, etc. These actions that each object can perform are called methods and in C++ they are basically functions that have been declared inside the body of an object. Technically the properties and methods are being declared inside the body of a class and not an object. Avoiding many technical details, you can think of a class as a concept and the objects as the embodiment of that concept. For example, in a circuit simulation where there would be three servo motors, you would first need to declare a class "Servo" and each one of these three motors would be a Servo object, or as it is commonly called an instance of the class Servo. 2177-1445 Class Object className objectName; objectName.classMethod(); Object Method
Exercises 1 Read the sentences and tick ✓ True or False. 1, loT devices can lock the doors of a residence. 2. You cannot monitor a smart home application from a smartphone. 3. Legislation is up to date on current issues regarding lot smart security applications. 4. Smart camera systems can be accessed only by the residence's network. 5. Smart home systems can automatically contact first responder services. 6. Smart lock systems can use biometric data to identify users. 7. C++ is a completely different language than C. 8. C++ is an object-oriented language. 9. C++ arrays are always type-defined. 10. The setup() and loop() functions are not important in an Arduino program. 2 Identify the benefits provided by smart security loT applications. وزارة التعليم True False • 4 • 233
224 3 Identify the potential risks of advanced smart security loT applications. 4 Classify the most common loT enabled smart home devices وزارة التعليم
5 Define the basic data types of a C++ program. 6 Analyze the fundamental rules of naming C++ variables. وزارة التعليم 235
221197 7 Demonstrate how "for" loops are implemented in C++. 8 Describe the difference between the "while" and "do... while" loops in C++. وزارة التعليم 1021-1445
9 State the use of the setup() and loop() functions in an Arduino sketch 10 Analyze how an electronic component connected to an Arduino board can be abstracted to a C++ class and object. وزارة التعليم 227