# 2023-04-11-NCL # Introduction to the Internet of Things workshop # This document: https://hackmd.io/@rseteam-ncl/2023-04-11-NCL PLEASE SIGN IN BELOW ## Links: ### Who we are: Jannetta Steyn, Samantha Finnigan, Stuart Lewis, Yash Borikar ### This document: https://hackmd.io/@rseteam-ncl/2023-02-21-NCL ### Workshop website: [Workshop Website](https://nclrse-training.github.io/2023-04-11-NCL/) ### Code of Conduct: [Code of Conduct] (https://docs.carpentries.org/topic_folders/policies/code-of-conduct.html) ### Coffee and Lunch 11:30 coffee, 13:00 Lunch, 15:30 coffee ### Lesson: [Lesson Website](https://carpentries-incubator.github.io/iot-novice/index.html) ### Arduino website: https://www.arduino.cc/ ### Arduino Unofficial ESP32 Board Manager URL: - https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json - UART Bridge: https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers?tab=downloads **Select: CP210x Windows Drivers v6.7.6 9/3/2020** ### Link for downloading MQTTx https://mqttx.app/ --- ## Surveys ### Pre-workshop Survey: https://forms.office.com/e/hmV32ArjbP ### Post-workshop Survey: https://forms.office.com/e/1vqtwM3Mge --- ## Attendance ### Please sign in with your <span style="color:red">university_email, your_name, University</span>: 1. >Isabella Bovolo, isabella.bovolo@durham.ac.uk, Durham University 1. >Markus Hussner, markus.husner@durham.ac.uk, Durham University 1. >Diana Martinez-Trejo, diana.o.martinez-trejo@durham.ac.uk, Durham University 1. >Rachel Wu, c2057617@newcastle.ac.uk, Newcastle University 1. >Sarath chandran Sivaji, c1048559@newcastle.ac.uk, Newcastle University 1. >Siti Khadijah Hamzah,siti.k.hamzah@durham.ac.uk, Durham University. 2. >Olusegun Adeniji, olusegun.a.adeniji@durham.ac.uk, Durham University 3. > 4. > 5. > 6. > 7. > 8. > 9. > 10. > 11. > 12. > 13. > 14. > 15. > 16. > ## Notes - Access Point: raspi-webgui - Password: carpentries # Linux serial install `sudo apt-get install python-pyserial` `sudo apt-get install python-pip` `sudo pip install pyserial` # Code snippets ```// This program will print numbers starting at the value allocated to the // variable `minimum` up to the variable called `maximum` // declare a constant of type integer called minimum const int minimum = 0; // declare a constant of type integer called maximum const int maximum = 100; // delcare a variable of type float called pi // a float type is a number that a decimal point. float pi = 3.14159265358979; void setup() { // Initialise the `Serial` library and tell it what speed to // use for communication with the computer via the USB port // The Serial library is included in the language by default // so we don't have to import it. Serial.begin(9600); } void loop() { // Use a loop structure to count from minimum to maximum // Notice the `int i` variable that is used as the counter // To understand the for-loop structure, read it as: // For i equals minimum to i less-than-or-equal-to maximum, // increment i by one (the ++ means increment by 1) for (int i = minimum; i <= maximum; i++) { // create a new value called multiply_pi and allocate // the value of `i * pi` to it float multiply_pi = i * pi; // Use the print function in the Serial library to // print `i` to the Serial Monitor Serial.println(multiply_pi); } // create a delay of 5000 milliseconds (5 seconds) delay(5000); // After the delay the microcontroller will start at the // beginning of loop() and run all the code inside it again. } ``` ## DHT 11 code ``` #include <DHT.h> #define DHT_SENSOR_TYPE DHT22 #define DHT_SENSOR_PIN 32 // ESP32 pin connected to DHT sensor const int readingdelay = 3000; DHT dht_sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE); void setup() { Serial.begin(9600); // initialize serial Serial.println(F("Starting ...")); dht_sensor.begin(); // initialize the DHT sensor } void loop() { float temperature = dht_sensor.readTemperature(); // read temperature in Celsius if (isnan(temperature)) { Serial.println("Failed to read from DHT sensor!"); } else { char tempString[8]; dtostrf(temperature, 1, 2, tempString); Serial.print("Temperature: "); Serial.println(temperature); } // wait a 3 seconds between readings delay(readingdelay); } ``` # ldr ``` #define LIGHT_SENSOR_PIN 32 // ESP32 pin GIOP36 (ADC0) const int readingdelay = 3000; void setup() { Serial.begin(9600); // initialize serial Serial.println(F("Starting ...")); } void loop() { int lightlevel = analogRead(LIGHT_SENSOR_PIN); // read light level Serial.print("Light: "); Serial.println(lightlevel); // wait a 3 seconds between readings delay(readingdelay); } ``` # Ohm's Law: ## V=I/R V = Voltage I = Current R = Resistance So if `R` is HIGH, `I` will be LOW If `R` is LOW, `I` will be HIGH We have `V` so can rearrange to get the current flow # Combining the two sensors ``` #include <DHT.h> #include <WiFi.h> #define DHT_SENSOR_TYPE DHT11 #define DHT_SENSOR_PIN 32 // ESP32 pin connected to DHT sensor #define LIGHT_SENSOR_PIN 36 // ESP32 pin GIOP36 (ADC0) const int readingdelay = 3000; DHT dht_sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE); void setup() { Serial.begin(9600); // initialize serial Serial.println(F("Starting ...")); dht_sensor.begin(); // initialize the DHT sensor } void loop() { float temperature = dht_sensor.readTemperature(); // read temperature in Celsius int lightlevel = analogRead(LIGHT_SENSOR_PIN); // read light level if (isnan(temperature)) { Serial.println("Failed to read from DHT sensor!"); } else { /* When reading the temperature and light levels, we get the values as numbers, but when we send it to the MQTT broker the values have to be converted to strings. We therefore have to declare variables of type char into which the number values can be transferred */ char tempString[8]; char lightString[8]; // Print the temperature to the monitor Serial.print("Temperature: "); Serial.println(temperature); // Print the light level to the monitor Serial.print("Light: "); Serial.println(lightlevel); // wait a 3 seconds between readings delay(readingdelay); } } ``` # MQTT ``` #include <DHT.h> #include <WiFi.h> #include <PubSubClient.h> #define DHT_SENSOR_TYPE DHT11 #define DHT_SENSOR_PIN 32 // ESP32 pin connected to DHT sensor #define LIGHT_SENSOR_PIN 36 // ESP32 pin GIOP36 (ADC0) const int readingdelay = 3000; const char* ssid = "raspi-webgui"; const char* password = "carpentries"; const char* mqtt_server = "10.3.141.1"; const String your_name = "/JohnSmith"; DHT dht_sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE); WiFiClient espClient; PubSubClient client(espClient); String topic_temperature = "/dht11" + your_name + "/temperature"; String topic_light = "/ldr" + your_name + "/light"; void setup() { Serial.begin(9600); // initialize serial Serial.println(F("Starting ...")); dht_sensor.begin(); // initialize the DHT sensor setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); float temperature = dht_sensor.readTemperature(); // read temperature in Celsius int lightlevel = analogRead(LIGHT_SENSOR_PIN); // read light level if (isnan(temperature)) { Serial.println("Failed to read from DHT sensor!"); } else { /* When reading the temperature and light levels, we get the values as numbers, but when we send it to the MQTT broker the values have to be converted to strings. We therefore have to declare variables of type char into which the number values can be transferred */ char tempString[8]; char lightString[8]; /** * Transfer the number values into strings */ dtostrf(temperature, 1, 2, tempString); dtostrf(lightlevel, 1, 2, lightString); // Print the temperature to the monitor Serial.print("Temperature: "); Serial.println(temperature); // Publish the temperature to the MQTT broker publishMQTT(topic_temperature, tempString); // Print the light level to the monitor Serial.print("Light: "); Serial.println(lightlevel); // Publish the light level to the MQTT broker publishMQTT(topic_light, lightString); // wait a 3 seconds between readings delay(readingdelay); } } void setup_wifi() { delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void callback(char* topic, byte * message, unsigned int length) { Serial.print("Message arrived on topic: "); Serial.print(topic); Serial.print(". Message: "); String messageTemp; for (int i = 0; i < length; i++) { Serial.print((char)message[i]); messageTemp += (char)message[i]; } Serial.println(); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { // Create a random client ID String clientId = "ESP32Client-"; clientId += String(random(0xffff), HEX); Serial.print(clientId + " attempting MQTT connection..."); // Attempt to connect if (client.connect(clientId.c_str(), "jannetta", "f0r3v3rl1n8x")) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(500); } } } void publishMQTT(String topicString, char payload[8]) { unsigned int length = topicString.length() + 1; char topic[length]; topicString.toCharArray(topic, length); Serial.print(topic); Serial.print(": "); Serial.println(payload); client.publish(topic, payload, true); } String byteArrayToString(byte * byteArray, unsigned int length) { String messageTemp; for (int i = 0; i < length; i++) { messageTemp += (char)byteArray[i]; } return messageTemp; } ```