MODULE 06

IoT & AI Basics

Connect the physical world to the internet & intelligence

MQTT ProtocolCloud DashboardsSmart HomeML with Python

What is IoT?

The Internet of Things (IoT) connects everyday physical devices to the internet, allowing them to send data, be monitored remotely, and respond to commands from anywhere in the world.

DEVICES ESP32 Sensor Smart Light Thermostat Door Lock Water Meter WiFi CLOUD MQTT Broker Database ThingSpeak API USER Phone App Dashboard Email Alerts Voice Control
15.9B
IoT Devices in 2025
MQTT
Most Common Protocol
ESP32
Best Beginner Board

MQTT Protocol

MQTT (Message Queue Telemetry Transport) is a lightweight publish-subscribe protocol designed for IoT devices with limited bandwidth. Devices publish messages to "topics" and others subscribe to receive them.

HOW MQTT WORKS

PUBLISHER ESP32 Sensor publish("temp", 27) BROKER broker.hivemq.com Routes messages Port 1883 SUBSCRIBER Phone App SUBSCRIBER Dashboard
// ESP32 MQTT Publisher // Install: PubSubClient library in Arduino IDE #include <WiFi.h> #include <PubSubClient.h> const char* ssid = "Your_WiFi"; const char* password = "password"; const char* mqtt_server = "broker.hivemq.com"; WiFiClient espClient; PubSubClient client(espClient); void setup() { WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) delay(500); client.setServer(mqtt_server, 1883); } void loop() { if (!client.connected()) { client.connect("ESP32Client"); } client.loop(); float temp = 27.5; // read from DHT11 char msg[10]; sprintf(msg, "%.1f", temp); client.publish("aawiskar/temperature", msg); delay(5000); }

ThingSpeak Dashboard

ThingSpeak is a free IoT cloud platform that lets you store sensor data and create beautiful charts without any server setup. It's perfect for beginners.

  • 1

    Sign up free at thingspeak.com (MathWorks account). Create a new "Channel" and add fields like "Temperature", "Humidity".

  • 2

    Copy your Channel's Write API Key β€” this is what the ESP32 will use to send data.

  • 3

    Upload the code below to your ESP32. It will send sensor readings to ThingSpeak every 15 seconds.

  • 4

    In ThingSpeak, go to your channel and click "Private View" β€” you'll see live charts updating in real time!

#include <WiFi.h> #include <ThingSpeak.h> #include <DHT.h> DHT dht(4, DHT11); WiFiClient client; unsigned long channelID = YOUR_CHANNEL_ID; const char* apiKey = "YOUR_WRITE_API_KEY"; void setup() { dht.begin(); WiFi.begin("SSID", "password"); while(WiFi.status() != WL_CONNECTED) delay(500); ThingSpeak.begin(client); } void loop() { float temp = dht.readTemperature(); float hum = dht.readHumidity(); ThingSpeak.setField(1, temp); ThingSpeak.setField(2, hum); ThingSpeak.writeFields(channelID, apiKey); delay(15000); // ThingSpeak free: min 15s between updates }

Blynk App Control

Blynk lets you build a custom phone dashboard to control hardware in real time. Toggle relays, read sensors, and create gauges β€” all from a drag-and-drop interface.

// Blynk IoT β€” Control LED from phone // Install Blynk library, create project at blynk.cloud #define BLYNK_TEMPLATE_ID "YOUR_TEMPLATE_ID" #define BLYNK_AUTH_TOKEN "YOUR_AUTH_TOKEN" #include <BlynkSimpleEsp32.h> char auth[] = BLYNK_AUTH_TOKEN; char ssid[] = "Your_WiFi"; char pass[] = "password"; // Called when Virtual Pin V1 changes in app BLYNK_WRITE(V1) { int pinValue = param.asInt(); digitalWrite(2, pinValue); // control LED/relay } // Send sensor data to app every 2 seconds BlynkTimer timer; void sendSensor() { float temp = 26.8; // read from sensor Blynk.virtualWrite(V2, temp); } void setup() { Blynk.begin(auth, ssid, pass); timer.setInterval(2000L, sendSensor); } void loop() { Blynk.run(); timer.run(); }

🌑️ WiFi Weather Station

Build a complete weather monitoring station that displays temperature, humidity, and pressure on an OLED and uploads data to the cloud every minute.

HARDWARE SETUP

ESP32 DevKit DHT22 (Temp+Humidity) BMP280 (Pressure) SSD1306 OLED 128x64 3D Printed Enclosure
#include <WiFi.h> #include <DHT.h> #include <Adafruit_BMP280.h> #include <Adafruit_SSD1306.h> DHT dht(4, DHT22); Adafruit_BMP280 bmp; Adafruit_SSD1306 display(128, 64, &Wire); void loop() { float t = dht.readTemperature(); float h = dht.readHumidity(); float p = bmp.readPressure() / 100.0F; // hPa float alt = bmp.readAltitude(1013.25); // sea level pressure display.clearDisplay(); display.setTextSize(1); display.setCursor(0, 0); display.printf("Temp: %.1f C\nHum: %.1f%%\nPress:%.0f hPa\nAlt: %.0f m", t, h, p, alt); display.display(); // Upload to ThingSpeak every 15s... delay(15000); }

🏠 Smart Home System

Control multiple home devices (lights, fans, door locks) from your phone using ESP32 + MQTT. A mini home automation system using just a few relays!

// Smart Home β€” control 4 relays via MQTT // Topics: home/light1, home/light2, home/fan, home/lock #include <WiFi.h> #include <PubSubClient.h> const int relays[] = {26, 27, 28, 29}; // relay pins const char* topics[] = { "home/light1", "home/light2", "home/fan", "home/lock" }; void callback(char* topic, byte* payload, unsigned int length) { String msg = ""; for (int i=0; i<length; i++) msg += (char)payload[i]; for (int i=0; i<4; i++) { if (String(topic) == topics[i]) { digitalWrite(relays[i], msg == "ON" ? LOW : HIGH); // LOW = ON for most relay modules (active low) } } }
πŸ“± Control from Anywhere: Use MQTT Dash or IoT MQTT Panel app on your phone. Create buttons that publish "ON"/"OFF" to your topics. As long as both the ESP32 and your phone are connected to the internet, it works from anywhere on Earth!

πŸ“ GPS Location Tracker

Track the real-time location of anything β€” a vehicle, a pet, or a package β€” using a GPS module and ESP32, viewable on Google Maps.

// GPS Tracker with ESP32 + Neo-6M GPS Module // GPS TX β†’ ESP32 RX2 (pin 16) #include <TinyGPS++.h> TinyGPSPlus gps; HardwareSerial gpsSerial(2); void loop() { while (gpsSerial.available()) gps.encode(gpsSerial.read()); if (gps.location.isUpdated()) { float lat = gps.location.lat(); float lng = gps.location.lng(); float speed = gps.speed.kmph(); Serial.printf("Lat: %.6f, Lng: %.6f, Speed: %.1f km/h\n", lat, lng, speed); // Send to server: // POST https://yourserver/location?lat=27.7&lng=85.3 } }
πŸ—ΊοΈ View on Maps: Send coordinates to a Google Sheets via Apps Script (free!), or use Traccar (open source tracking server). You can also open this URL on your phone: maps.google.com/?q=LAT,LNG and bookmark it.

What is Machine Learning?

Traditional programming: you write rules β†’ computer follows them. Machine learning: you show examples β†’ computer learns the rules itself. ML enables computers to improve with experience.

TRADITIONAL Data β†’ RULES β†’ Answer You write every rule Brittle, hard to maintain if temp > 30: turn_on_AC() MACHINE LEARNING Data + ANSWERS β†’ Rules Computer learns patterns Adapts to new data model.predict(new_data)
🧠 3 Types of ML:
Supervised β€” learns from labeled examples (spam detection, image classification)
Unsupervised β€” finds hidden patterns in unlabeled data (clustering, anomaly detection)
Reinforcement β€” learns by trial and error (game AI, robot navigation)

Scikit-Learn Basics

Scikit-learn is Python's most popular machine learning library. It makes training models as simple as calling .fit() and .predict() β€” just three lines for a working classifier!

# pip install scikit-learn pandas matplotlib numpy from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score import pandas as pd # 1. Load data iris = load_iris() X, y = iris.data, iris.target # features, labels labels = iris.target_names # ['setosa','versicolor','virginica'] # 2. Split: 80% train, 20% test X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) # 3. Train model model = KNeighborsClassifier(n_neighbors=3) model.fit(X_train, y_train) # 4. Evaluate predictions = model.predict(X_test) accuracy = accuracy_score(y_test, predictions) print(f"Accuracy: {accuracy * 100:.1f}%") # ~97% # 5. Predict new flower new_flower = [[5.1, 3.5, 1.4, 0.2]] # sepal_l, sepal_w, petal_l, petal_w pred = model.predict(new_flower) print(f"Predicted: {labels[pred[0]]}") # setosa
πŸ“Š Other Popular Algorithms: Decision Trees (interpretable), Random Forest (accurate), SVM (good for small data), Linear Regression (predicting numbers), Neural Networks (complex patterns). Start with KNN or Decision Trees β€” they're easiest to understand!

TensorFlow Lite on Microcontrollers

TensorFlow Lite Micro (TFLM) lets you run trained ML models directly on Arduino and ESP32 β€” enabling gesture recognition, voice commands, and anomaly detection at the edge, with no cloud required!

WORKFLOW: FROM PYTHON MODEL TO ARDUINO

# STEP 1: Train a model in Python import tensorflow as tf import numpy as np # Simple gesture classifier (3 gestures) model = tf.keras.Sequential([ tf.keras.layers.Dense(16, activation='relu', input_shape=(6,)), tf.keras.layers.Dense(16, activation='relu'), tf.keras.layers.Dense(3, activation='softmax') ]) model.compile(optimizer='adam', loss='categorical_crossentropy') model.fit(X_train, y_train, epochs=50) # STEP 2: Convert to TFLite converter = tf.lite.TFLiteConverter.from_keras_model(model) converter.optimizations = [tf.lite.Optimize.DEFAULT] # quantize! tflite_model = converter.convert() # STEP 3: Export as C array for Arduino with open('model.tflite', 'wb') as f: f.write(tflite_model) # Run: xxd -i model.tflite > model_data.h # Then include model_data.h in Arduino sketch
πŸš€ Getting Started: The easiest way to experience ML on microcontrollers is the Arduino Nano 33 BLE Sense β€” it has an IMU, microphone, and color sensor, and Tiny ML tutorials at tinyml.org. You can train a wake-word model ("Aawiskar!") and deploy it in an afternoon.