Lesson Designing and Programming a Smart Waste IoT Device - 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
Link to don Lesson 2 Designing and Programming a Smart Waste IoT Device www.len edusa Smart Waste Management Due to overpopulation, very large quantities of waste and garbage are not collected and processed efficiently, leading to waste overflows in various locations. This problem occurs because there are garbage cans that overflow and are not cleared on time. With smart waste cans, there can be alert messages that notify waste collection vehicles. Also, with the appropriate data analysis, we can derive insights into how waste cans are filled to optimize the whole process further. Message EMQX PLATI OFM Message Figure 7.8: Smart Waste Management Arduino & MOTT project In this lesson, you will build a prototype of a smart garbage can that counts how many actions on average are required to reach full capacity. A message is sent to an MQTT broker each time the can is used. When the can is full, another message is sent to the system's controller mit that generates reports for the can. For this project, you will use an Arduino microcontroller that represents the smart trash can, which you will program with the Firmata protocol and Python, and use the EMQX platform to distribute the messages. 173-1445 EMQX EMQX is an open-source MQTT broker with a high-performance real-time message processing engine. It is used to support event streaming for an extremely large number of loT devices. 273
Components & Tools for Project Phototransistor A Phototransistor is an electrical component that operates when exposed to light When light falls upon the sensor, a proportionate amount of reverse current flows. Phototransistors are widely employed to detect and convert light pulses to electrical signals. Phototransistor Q1 CE Simulator component Schematic symbol Figure Phototranstor Tilt Sensor A tilt sensor is used to measure a reference plane's tilt along multiple axes. Tilt sensors assess the tilting position relative to gravity and are employed in various applications. They make orientation or inclination detection simple. وزارة التعليم 077-1985 274 Simulator component figure 7.10 Til Sunv UT 00+ Schemabe symbo
Arduino Prototype The Arduino microcontroller will monitor the state of the can and collect the action data to send through the Firmata protocol. The tilt sensor will be used to record each time the can is used, simulating the movement of the can's lid and the phototransistor as a light sensor, so that when it reaches a certain threshold, it will mean the can is full of garbage. You will need the following components: • 1 Arduino Uno R3 ⚫1 Breadboard Small ■1 Phototransistor • 1 Tilt Sensor ⚫ 2 Resistors (1k) Components that you will use in this project وزارة التعليم 3123-185 OO UNO Arduino Uno R3 Phototransistor Tilt Sensor Resistors Figure 71 Smart Waste project components Breadboard Small 275
Connecting to the EMQX Public Broker You will first need to install the MQTTX client desktop application and then test the connection with the EMQX public broker. To install the MQTTX client application go to the website: https://mqttx.app/ and download the latest version, Run the installer to complete the installation process. You will now open the client and create a new connection to the EMQX broker. Anos MUITY 2 MQTTX Sup Search the web To set up the connection to the EMQX broker with MQTTX: > Click the Windows search button and type MQTTX. > Open the MQTTX client desktop app. > Click New Connection, to create a new connection. > Type a name for the connection e g. desktop_connection. >Click on the Connect button. max download matt logic u requin ed MOTTX دات التعليم 2173-1865 276 Connections Pat S A 3 New 5 Figure 712 Setting up the connection to the MQX broker with MQTTX
Arduino Circuit You will begin building the Arduino circuit by putting the required components into the Tinkercad circuits workplane. To load the components: > Find the Arduino Uno R3 from the components library and drag and drop it into the workplane. > Find the Breadboard Small from the components library and drag and drop it into the workplane. > Find the Ambient Light Sensor [Phototransistor] from the components library and drag and drop it into the workplane. > Find the Tilt Sensor 4-pin from the components library and drag and drop it into the workplane. C > Find the Resistor from the components library and drag and drop 2 of them into the workplane. Set Warmi وزارة التعليم 2 1 5 3 All Figure 13, Loading the components of the rout 277
278 To connect the Phototransistor. > Connect the Emitter end of the Phototransistor to Analog Pin AO of the Arduino and change the wire color to yellow. > Connect Terminal 2 of the one. Resistor to the same row as the Emitter of the Phototransistor and connect Terminal 1 of the Resistor to the negative column of the Breadboard Small. > Connect the Arduino UNO R3 5V pin to the positive column of the Breadboard and change the wire color to red. > Connect the Arduino UNO R3 ground pin to the negative column of the Breadboard and change the wire color to black. > Connect the Collector end of the Phototransistor to the positive column of the Breadboard Small. DIGITAL GWM OO UNO ARDUINO TOWET 1 3 Figure 714 Connect Line Phototransistor To connect the Tilt Sensor. > Connect Terminal 2 of the other Resistor to Terminal 2 of the Tilt Sensor. > Connect Terminal 2 of the Tilt Sensor to Digital Pin 3 of the Arduino and change the wire color to green. > Connect Terminal 4 of the Tilt Sensor to the positive column of the Breadboard Small and change the wire color to red. > Connect Terminal 1 of the Resistor to the negative column of the Breadboard Small and change the wire color to black. DIGITALWI DO UNO وزارة التعليم 2173-1445 2 Figure 7.15 Connect the Till Sensor 5 3
Complete Circuit OO LINE Physical Circuit Heure 7.16. Carmahete circuit in Tinkercad This photo represents what the physical circuit will look like. 8 DUING The components are connected to the following phits: وزارة التعليم 173-1445 Figure 7.18 Photo of the physical circuit AO figure 7.17 Pins connected to components D3 279
280 Programming the Arduino You will begin by uploading the Standard Firmata sketch through the Arduino IDE to setup a communication channel between the Arduino and the Python script that you will write. Open PyCharm and install the paho-matt Python package through pip. In PyCharm, open the terminal in your working directory and enter the following command: pip install pahe-mqtt Create a new Python file called mqtt_arduino.py and at the beginning of your code import the following packages: ■ datetime: Create timestamps for the messages that we send. ■time: Control the program flow. ■ json: Work with JSON objects. ⚫pyfirmata: Communicate with the Arduino board through the Firmata protocol. ⚫paho.mqtt.client: Create clients that communicate with MQTT brokers. from datetime import datetime import time import json import pyfirmata import paho.mqtt.client as mq Create the following variables which will be used for the MQTT client that we will create. CLIENT_ID is the name you will give to client. MQTT BROKER is the address of the public broker provided by EMQX that you will connect to. TOPIC is the name of the topic that the client will subscribe to. PORT is the default server port to connect to the MQTT broker. FLAG_CONNECTED is a flag variable you will use on an event handler function later. # Variables to setup MQTT client CLIENT_ID = "PUBLISHER_01" # ID of the client MQTT BROKER = "broker.emqx.io" # Address of the broker ■TOPIC "ase/drops" -PORT"1883 # Topic to subscribe to # Default server port FLAG CONNECTED = False # Connection flag ل التعليم 2193-1485
Table 7.3: MQTT Broker Connection Variables Variable CLIENT_ID MQTT BROKER TOPIC PORT FLAG_CONNECTED Description The name of the MQTT client, Address of the target MQTT broker The topic that the client will subscribe to The server port to connect to Flag variable to check server connection. Add the following lines that initialize a connection to the Arduino with the Firmata protocol and set the two pins for the light and tilt sensor we will use to get our data. board pyfirmata.Arduino('COM4!) # Specify communication port it = pyfirmata.util. Iterator(board) # Select the board to connect it.start() # Connect to board. # Selecting the sensor pins Light sensor_pin = board.get_pin( 'a:0:1')) tilt sensor pinboard.get_pin('d:3:1') Create the following variables; can_full is a flag to set whether the can has been filled or not. garbage_drops is a counter to track how many uses were needed to fill the can. can_full = False # Flag to indicate whether the can is full = garbage drops # Counter for the garbage drops Create the following function which resets the can_full and garbage_drops variables every time the can is full, and next we publish a message to the client about it. def reset_can(): global garbage drops # Access the garbage drops variable global can full garbage drops = 0 can full False # Access the can_full variable # Reset the counter to # Clear the can وزارة التعليم 15 - כקוע 281
Create the following function to publish a message that the can was used to the client. You will first create a timestamp variable to record the time and create a dictionary object with the timestamp, garbage_drops and can_full properties. You will convert this dictionary to a JSON object and then publish it to the subscribed "waste/drops" topic through the client. def publish_message(): global garbage drops # Access garbage drops variable global can full # Access can full variable # Create a custom format for the timestamp timestamp = str(datetime.now().strftime("%H:%M:%S")) msg dictionary = { # Creating the JSON object } "timestamp": timestamp, "garbage drops": garbage drops, msg = try: "can_full": can_full json.dumps(msg_dictionary) # Convert dictionary to JSON result client.publish(TOPIC, msg) # Publish message except: print("There was an error while publishing the message*) time.sleep(2) Create the following event handler function that prints a confirmation message to the terminal about whether or not the connection to the client was successful. The function's arguments are default arguments that must be used to bind that function to the appropriate event handler provided by the paho.mqtt.client library. def on_connect(client, userdata, flags, rc): global FLAG CONNECTED # Access the FLAG CONNECTED variable if rc == 0: # If rc is the client connected successfully FLAG CONNECTED = True print("Connected to MQTT Broker!") وزارة التعليم 273-1945 282 else print("Failed to connect to MQTT Broker!")
In the main part of the program, you will initialize the MQTT client, bind the on_connect event handler to the above function, connect to the specified MQTT broker, and subscribe to the specified topic. client mq.Client(CLIENT_ID) client.on_connect = on_connect # Initialize an MQTT client # Bind the on connect event handler client.connect(MQTT BROKER, PORT) # Connect to the specified MQTT broker client.subscribe(TOPIC, 0) # Subscribe to the specified topic Create the main loop for the program. If the light value has a value of less than 0.200 then the can is considered full. while True: #Get sensor values light_value = tilt_value == light sensor pin.read() tilt sensor pin.read() if (light value is not None) and (tilt_value is not None): print("Light levels " str(light_value)) print("Tilt levels: + str(tilt_value)) وزارة التعليم 123-1445 print("Garbage drops "str(garbage drops)) # If there is a tilt, add 1 to the counter if (tilt_value == True): garbage drops += 1 # If there is a tilt and the can is full # publish a message and reset the can if (light value <= 0.200): can full True publish_message() reset_can() publish_message() time.sleep(1) Z83
284 Complete Code from datetime import datetime import time import json import pyfirmata import palio.mall.client as ma # Variables to setup MQTT client CLIENT_ID = "PUBLISHER_01" MQTT BROKER = "broker.emqx.io" = TOPIC "waste/drops" PORT = 1883 #10 of the client # Address of the broker # Topic to subscribe to # Default server port FLAG_CONNECTED = False # Connection flag board pyfirmata. Arduino('COM4') # Specify communication port it pyfirmata.util.Iterator(board) # Select the board to connect # Connect to board it.start() # Selecting the sensor pins = light sensor pin board.get_pin( 'a:0:1) tilt sensor pin board.gel pin('d:3:1') can full False garbage drops = @ # Flag to indicate whether the can is full # Counter for the garbage drops def reset_can(): global garbage drops # Access garbage drops variable global can full garbage drons=0 # Access can full variable # Reset the counter to B وزارة التعليم False # Clear the can
def publish_message(): global garbage_drops # Access garbage drops variable global can_full # Access can full variable # Create a custom format for the timestamp timestamp str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) # Creating the dictionary object msg dictionary = { "timestamp": Limestamp, "garbage drops": garbage drops, "can_full" can_full 7 msg = json.dumps(msg_dictionary) # Convert dictionary to JSON try: result = client.publish(TOPIC, msg) # Publish message except: print("There was an error while publishing the message") time.sleep(2) print("Message sent to the MQTT broker") def on_connect(client, userdata, flags, rc): global FLAG CONNECTED # Access the FLAG CONNECTED variable if rc == 0: # If rc is the client connected successfully FLAG CONNECTED = True print Connected to MQTT Broker!") قراره الي البدر 2105-1985 print("Failed to connect to MQTT Broker!") 265
client mq.client (CLIENT_ID) client.on_connect on connect # Initialize an MQTT client # Bind the an connect event handler client.connect(MQTT BROKER, PORT) # Connect to the specified MQTT broker # Subscribe to the specified topic client.subscribe(TOPIC, B) while True: # Get sensor values light value light sensor_pin.read() tilt_value tilt sensor pin.read() if (light_value is not None) and (tilt_value is not None): print("Light levels: " + print("Tilt levels : str(light_value)) str(till value)) print("Garbage drops: + str(garbage drops)) # If there is a tilt, add 1 to the counter if (tilt_value == True); garbage drops += 1 # If there is a tilt and the can is filled # publish a message and reset the can if (light value <= 0.200): can full True publish_message() reset_can() publish_message() time.sleep(1) وزارة التعليم 13-1445 28G
Testing the Broker EMQX is a public MQTT broker for testing and developing MQTT applications. It aids in developing loT application protypes without the cost of infrastructure and the development of the broker. You will use the MQTT X client to test the publishing of our messages. You will later create another Python script that will receive the published messages, generate reports for the can and perform data analysis on those reports. After you have uploaded the StandardFirmata sketch to the Arduino, execute the Python script and move the breadboard to activate the tilt sensor. Every time it is activated, the garbage count tracker will count up. When you activate the tilt sensor with the light sensor covered, the program will publish a message that the can is full, resetting the garbage counter. In the next lesson you will perform data analysis on the data from the published messages. To test that your messages were published correctly you will use the MQTTX desktop client. Before executing the Python script you will use the MQTTX client to subscribe to the "waste/drops" topic. Now the client will wait to receive the messages that are published through the Python script and are distributed through the EMQX public broker. To use MQTTX to subscribe to the specified topic: Connections desktop connection > On the menu of the desktop_connection connection, click on the New Subscription button. > On the Topic textbox, enter the text waste/drops. > Click on the Confirm button. New Sulzeration 2 Qut M a MOTOR 101 10 tree 3 1 CSME Figure 719 Using MQTTX to subscribe to the specified topic 287
288 Viewing Messages through the MQTTX Client After you have executed the Python script and it begins to publish messages, you will receive those messages in the MQTTX desktop client like this. 3 Connections desktop.connection وزارة التعلم Figlire 720 Viewing messages though the MQTTK client
Exercises 1 Create a diagram of an MQTT network with one Arduino as the publisher and two other Arduinos as the receivers. 2 Describe the phototransistor and tilt sensor components and their use cases. وزارة التعليم 00-1445 289
200 3 Analyze what the public EMQX broker is and how it alds in developing loT prototype applications. 4 Update the event handler for the on_connect event that prints to the console the configuration info that you provided to the MQTT client. 5"Update the publish_message() function to publish a message with a timestamp that presents the complete date and time and a new property that contains the client Per 21-1445
6 Create a Python script that lets the user type the topic they want to subscribe to and the message they want to send and then publishes it through the public EMQX broker. Test your script with the MQTT X desktop client. وزارة التعليم W-1445 291