Lesson Microcontroller Programming 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
Lesson 3 Microcontroller Programming with C++ Build a Smart Door Lock In this project the components you are going to use are Arduino Uno R3 • Keypad 4x4 ⚫ LCD 16x2 (12C) • Micro Servo Components that you will use in this project LCD 16x2 (12C) 00 ME Arduino Uno R3 2103-179 242 Micro Servo Rgule 17 Project components Link to digital lesson www.len.etisa Keypad 4x4
You will start by adding the keypad from the input category in the components and connect it to Arduino. Connecting the Keypad. > Find the Keypad 4x4 component from the Input category in the components list and drag and drop it in the workplane. > Connect the Row 1 of the Keypad to the Digital Pin 9 of the Arduino. > Connect the Row 2 of the Keypad to the Digital Pin 8 of the Arduino. > Connect the Row 3 of the Keypad to the Digital Pin 7 of the Arduino. > Connect the Row 4 of the Keypad to the Digital Pin 6 of the Arduino. > Connect the Column 1 of the Keypad to the Digital Pin S of the Arduino. > Connect the Column 2 of the Keypad to the Digital Pin 4 of the Arduino. > Connect the Column 3 of the Keypad to the Digital Pin 3 of the Arduino. > Connect the Column 4 of the Keypad to the Digital Pin 2 of the Arduino. > Change all wires color to green. زارة التعليم 1 日 D 2 4 6 8 3 5 7 9 DIGITAL (PWM-) Figure 6 18. Comecting the Keypad 243
Now, find the LCD display from the ouput category in the components and connect it to the Breadboard. Connecting the LCD display: > Find the LCD 16x2 (12C) component from the Output category in the components list and drag and drop it in the workplane. > Connect the Ground of the LCD to the GND of the Arduino and change the wire color to black. > Connect the Power of the LCD to the 5V of the Arduino and change the wire color to red. > Connect the SDA of the LCD to the SDA of the Arduino and change the wire color to green. > Connect the SCL of the LCD to the SCL of the Arduino and change the wire color to yellow. وزارة التعليم 2173-1465 244 DIGITAL PWM BUND 25 ARDUINO POWER ANALOGIN Figure 1: Connecting the LCD display 2 4410 3 5 1
Finally, you will wire the Servo motor. Find the Servo motor from the ouput category in the components and connect it to the Breadboard. Connecting the Servo motor; > Find the Micro Servo component from the Output category in the components list and drag and drop it in the workplane. > Connect the Ground of the Servo motor to the GND of the Arduino and change the wire color to black. > Connect the Power of the Servo motor to the 5V of the Arduino and change the wire color to red. > Connect the Signal of the Servo motor to the Digital Pin 11 of the Arduino and change the wire color to orange. حرارة اسعايد 0 D 4 1 3 2 Figure 6-20 Connecting the Servo moter 245
246 Include the Libraries Apart from the Arduino controller, to use the rest of the components and program their logic in C++ you first need to include their libraries in the code section of the Tinkercad platform. These libraries provide many functions specific to each component. To include a library in C++ you need to type: #include <library name> For the current project, you need the following libraries. For the LCD panel #include <Adafruit_LiquidCrystal.h> for the keypad #include <Keypad.h> for the servo motor #include <Servo.h> Create the Objects After including the necessary libraries, you need to create some objects and initialize some parameters. The objects that you need to create are ⚫ an LCD object, ⚫ a servo object, ⚫ a keypad object. When creating an object (or an instance) of a class, sometimes you need to provide some arguments to the constructor of this object. A constructor is a special class method that is called when an object is created, and it's functionality is to initialize the object's parameters. وزارة التعليم 211773-1445
servo motor object To create a servo motor object Servo servo; Where "Servo" is the object type and "servo" is the actual object that you use in the code. You don't need to provide any initialization parameters. Hgum 5.21. Survo motor Tinkercadoje LCD display object To create an LCD display object: Adafruit LiquidCrystal lcd(0); With this command, you initialize an object of type Adafruit_Liquid Crystal and pass its initial Ardumo address (which is 0 by default) as an argument to the constructor of the class. Hgure 5.22: LCD display (Tinkercard object) TEL Z Keymd Tinkercad ubject) Keypad object The creation and initialization of the Keypad object needs some setup code. At first you need to specify the number of rows and columns the Keypad has. You do this with the commands: const byte numRows = 4; // number of rows on the keypad const byte numCols = 4; // number of columns on the keypad Here, you specify that the number of rows (numRows) is of the type "const byte" and its value is 4. The same applies to numCols. وزارة التعليم 2173-1465 247
Then you need to define the key pressed according to the row and column exactly as it appears on the keypad. The way to do this is: // keymap defines the key pressed according to the rows and columns just as they appear on the keypad char keymap[numRows][numCols] = { '1' 2'3", "A"} 4', '5', 6', '87, {'7' 18', '9', 'C', {#, "D"} }; Here, you create the keymap array with the numRows and numCols you defined earlier and explicitly define the keys that are on the keypad. After that, you need to setup the keypad connections to the Arduino terminals. You do this by defining two variables of type byte: // Code that shows the the keypad connections to the arduino terminals byte rowPins[numRows] = 19,8,7,5); //Rows @ to 3 byte colpins[numCols] (5,4,3,2); //Columns to 3 The last step is to define a Keypad object by calling its constructor and providing the necessary arguments, // initializes an instance of the Keypad class = Keypad keypad Keypad (makeKeymap(keymap), rowPins, colpins, numRows, numCols); To conclude the setup code, you define a variable called password that will store the password of the door lock and it is an array of characters with length 4. char password[4]; وزارة التعليم 2173-1445 248
Break down the Code At this point, the setup code is completed. As we explained in Lesson 1, the Arduino controller executes the setup() function only once, when it is powered on and then executes the loop() function repeatedly. Let us break this code down. We use two servo functions from the Servo library. servo.attach(11), where we attach the Servo variable to pin 11 The code of the setup() function is: void setup() //servo setup servo.attach(11); servo.write(@); servo.write(0), which is used to write a value to the servo, in this case, it writes the value 0, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. After that, we use three functions of the Adafruit_LiquidCrystal library. These are: cd.begin(col.row) which initializes the interface to the LCD screen and specifies the dimensions (width) and height) of the display begin() needs to be called before any other LCD library commands. The arguments are: ⚫cols, which is the number of columns that the display has rows, which is the number of rows that the display has and because the LCD screen that you will use is 16x2 you give as arguments col-16 and row=2, hence lcd.begin(16,2); The last piece of code in the setup() function is a for loop which stores the 4-character password the user types on the Keypad, in the variable To do so the Keypad library function: 1123-15 7 //Lcd setup and password set led.begin(16, 2); lcd.setCursor(0, 0); lcd.print("Set 4 character"); lcd.setCursor(0, 1); lcd.print("password: "); = for(int i=0; i < 4; i++) { password[i] keypad.waitForKey(); } The next function is: lcd.setCursor(col,row) which sets the location at which subsequent text written to the LCD will be displayed. So, to display the phrase "Set 4 character password" you need both rows of the lcd screen. On the first row, the phrase "Set 4 character" will be displayed and on the second row the phrase "password" will be displayed. That's why before displaying the first phrase you call the function as lcd.setCursor(0, 0); and to display the second phrase you call the function as lcd.setCursor(0, 1); keypad.waitForKey() is called. This function. will get the key that was pressed and store it In the password.array. 249
Now for the main functionality of this project the loop() function will be getting called repeatedly. The code of the loop() function is: void loop() f clear the screen and display the new message lcd.clear(); Lcd.setCursor(0, 0); lcd.print("Enter password:"); bool correct Pass = true; char buttonPressed; this code checks each button pressed against the corresponding password digit fe.g. it will check the 1st button pressed against the first digit of the password and so on for (int i = 0; i < 4; i++) { buttonPressed = keypad.waitForKey(); if (password[i] != button Pressed){ correctPass = false; } } lcd.setCursor(i, 1); Tcd.print(buttonPressed); delay(1000); //this code will be executed if the password is correct if (correctPass) { per the led screen وزارة التعليم 173-1445 250 icd.clear();
1 - בקוע } } // set the cursor to the beginning of the 1st line lcd.setCursor(0, 0); lcd.print("Correct password!"); // set the cursor to the beginning of the 2nd line lcd.setCursor(0, 1); lcd.print("Unlocking..."); // write the angle by which the servo will rotate servo.write(186); // wait 5 sec and then rotate the servo to its original angle delay(5000); servo.write(0); else { // this code will be executed if the password is wrong // clear the led screen lcd.clear(); // set the cursor at the 1st col, row lcd.setCursor(0, 0); print the message lcd.print("Wrong password!"); Break this Code down To start with, there is some code to clear the lcd screen and display a message asking for the password. //clear the screen and display the new message cd clear; lcd.setCursor(0, 0); d.print("Enter password: "); 251
252 Then there is the code that takes the user-typed password and checks whether this code is correct or not. The way it does this is by comparing the buttons pressed one by one sequentially against the digit of the password that is in the same position. For example, let us say the password set in the beginning is "5456" and the user types the password "5453". Since every key that the user presses will be compared to the corresponding password key, what will happen is: 5 is compared to 5 (they are the same, so no problem so far) 4 is compared to 4 (still the same, still no problem) 5 is compared to 5 (still no problem) 3 is compared to 6 (they are not the same, so the password pressed is NOT correct). Whenever the code compares two keys that are not the same it should update a variable with the information that the password is not correct. It does not matter if the wrong key occurs at the first digit, last digit or anywhere in between. The complete password will be wrong. So, to store this information you can use a boolean variable that will be initialized as true and whenever a wrong key occurs, its value will be set to false. After the comparison is done, you can check the value of this variable and if that value is true it means the user typed the correct password. If that value is false, it means the user typed a wrong password. The functionality we just described is performed by this piece of code: bool correct Pass = true; char buttonPressed; // this code checks each button pressed against the corresponding password digit //e.g. it will check the 1st button pressed against the first digit of the password and so on for (int i = 0; i < 4; i++) { buttonPressed = keypad.waitForKey(); if(password[i] != button Pressed){ } correct Pass = false; lcd.setCursor(1, 1); led.print(buttonPressed); وزارة التعليم 2173-1985
What is left now, is to unlock the door (rotate the servo) if the password typed was correct and lock it again after a period of time, or to display a message saying the password was wrong. This functionality is performed by the code: // this code will be executed if the password is correct if(correctPass){ } clear the lcd screen. lcd.clear(); // set the cursor to the beginning of the 1st line lcd.setCursor(0, 0); lcd.print("Correct password!"); // set the cursor to the beginning of the 2nd line lcd.setCursor(0, 1); lcd.print("Unlocking..."); // write the angle by which the servo will rotate servo.write(180); // wait 5 sec and then rotate the servo to its original angle delay(5000); servo.write(0); else { // this code will be executed if the password is wrong // clear the led screen lcd.clear(); // set the curser at the 1st col, row Lcd.setCursor(0, 0); // print the message lcd.print("Wrong password!"); } وزارة التعليم 023-1445 253
254 Finally, the complete code for the door lock project is: Complete Code // C++ code 11 #include <Adafruit LiquidCrystal.h> #include <Keypad.h> #include <Servo.h> Adafruit Liquid Crystal lcd(0); Servo servo; Choose the programming mode of Text in the code editor. const byte numRows = 4; //number of rows on the keypad const byte numCols = 4; //number of columns on the keypad // keymap defines the key pressed according to the rows and columns just as they appear on the 7/keypad char keymap[numRows][numCols] = (1, 2, 3, "A"), '45', 6', 'B'}, {7, 8, 9", "Ch. ['*', '0', '#', '0'} }; Code that shows the the keypad connections to the arduino terminals byte rowPins [numRows] (9,8,7,5]; //Rows 0 to 3 = byte colpins[numCols) (5,4,3,2); //Columns 0 to 3 = // initializes an instance of the Keypad class Keyad keypad Keypad (makeKeymap (keymap), rowPins, colPins, numRows, numCols); ويليم العصا السحر 103-1445
char password[4]; void setup() f // servo setup servo.attach(11); servo.write(0); // lcd setup lcd.begin(16, 2); lcd print 1st line lcd.setCursor(0, 0); lcd.print("Set 4 character"); led print 2nd line. lcd.setCursor(0, 1); lcd.print("password: "); // gets and stores the password for(int i = 0; i < 4; i++){ password[i] = keypad.waitForKey(); } } void loop() { clear the screen and display the new message lcd.clear(); lcd.setCursor(0, 0); lcd.print("Enter password: "); corretas = true; char buttonPressed; وزارة التعليم 3000-1983 256
256 // this code checks each bulton pressed against the corresponding password digit // e.g. it will check the 1st button pressed against the first digit of the password and so on for(int i = 0; i < 4; i++) { buttonPressed = keypad.waitForKey(); if(password[i] != button Pressed) { correctPass false; } } lcd.setCursor(i, 1); lcd.print(button Pressed); delay(1000); //this code will be executed if the password is correct if (correctPass){ // clear the lcd screen lcd.clear(); // set the cursor to the beginning of the 1st line lcd.setCursor(0, 0); lcd.print("Correct password!"); // set the cursor to the beginning of the 2nd Line lcd.setCursor(0, 1); lcd.print("Unlocking..."); // write the angle by which the servo will rotate servo, write(180); // wait 5 sec and then rotate the servo to its original angle delay(5000); servo.write(0); etse. I de will be executed if the password is wrong 15 - בקלות
} // clear the lcd screen lcd.clear(); set the cursor at the 1st col, row lcd.setCursor(0, 0); // print the message lcd.print("Wrong password]"); وزارة التعليم 103-1445 After you have completed the program, click on the Start Simulation button. 257
258 Exercises 1 Create a circuit in Tinkercad that is connected to a temperature sensor and an LCD display. Then program it with C++ to display the temperature reading on the LCD display. Z Create a circuit in Tinkercad that is connected to a 4x4 keypad and an LCD display. Then program it with C++ to display the pressed characters on the LCD display. مرارة التعليم 00-1445
3 Create a circuit in Tinkercad that is connected to a 4x4 keypad and two LED lights, one RED and one green. The user will set a password and then will try to use it If the input is right, the green light will light up, and if it is wrong, the red light will blink repeatedly. 4 Create a circuit in Tinkercard that is connected to a soil moisture sensor and servomotor. Then program it with C++ to turn the servomotor when the soil moisture reaches a certain dryness. جرابة الكلية 259