CodeNFacts
CodeHub
Home

All Categories


Sign In
/ iot

The Internet of Things,
wired up from first principles.

A sensor reads the world, a network carries it, a system decides, and something physical reacts. That loop is the whole idea. This page walks through it - architecture, boards, sensors, protocols, cheat sheets, and the trick questions interviewers actually ask.

Boards & MCUsProtocolsSensorsLearn with AI
Node 01

What is IoT, really?

The Internet of Things is a network of physical objects — sensors, appliances, vehicles, machines — embedded with electronics and software that let them collect data and exchange it with each other or the cloud, usually with little to no human in the loop. It's not one technology; it's four layers stacked on top of each other, each doing one job:

Perception Layersensors & actuators — the physical worldNetwork LayerWi-Fi, BLE, LoRa, Zigbee — moves the dataProcessing Layeredge device, broker, cloud rules engineApplication Layerdashboard, alert, automated action

A single project rarely needs custom work at every layer — most tutorials start at Perception and stop at Network. The Processing and Application layers are where a toy project turns into a product.

Node 02

Why IoT matters now — and what the world looks like without it

Sensors got cheap, Wi-Fi chips got tiny, and cloud storage got nearly free — all in the same decade. That combination is why IoT went from research labs to every home in about ten years. Here's the difference it actually makes:

Without IoT

  • A factory motor is inspected on a fixed monthly schedule — it fails silently between checks.
  • A farmer waters on a calendar, not on actual soil moisture — wasting water or under-watering.
  • A patient's vitals are only known during a clinic visit, once every few months.
  • A city discovers a water leak from a resident's complaint, weeks after it started.

With IoT

  • Vibration sensors flag bearing wear weeks in advance — maintenance happens before failure.
  • Irrigation triggers only when soil moisture actually drops below threshold.
  • A wearable streams heart rate continuously, flagging anomalies the same day they occur.
  • Flow sensors on the water grid catch a leak within hours, not weeks.

Where it shows up

Smart Home

Lights, locks, thermostats, and plugs that react to presence, time, and voice — without a human flipping a switch.

Healthcare

Wearable heart-rate and SpO2 monitors stream vitals to a doctor's dashboard in real time, catching problems before an appointment would.

Agriculture

Soil-moisture and weather sensors trigger irrigation only when needed — cutting water use while protecting yield.

Industry 4.0

Vibration and temperature sensors on motors predict a bearing failure weeks before it happens, instead of after the line stops.

Smart Cities

Parking sensors, smart streetlights, and air-quality stations turn a city into a system that reports its own condition.

Wearables

Fitness bands and smartwatches fuse accelerometer, GPS, and heart data into a single picture of a person's day.

Node 03

How an IoT system actually works

Strip away the branding and almost every IoT product is the same five-node pipeline. Data flows right; decisions and commands can flow back left.

Sensorreads the worldMicrocontrollerESP32 / ArduinoGatewayWi-Fi / LoRa / BLEBroker / CloudMQTT, AWS IoTDashboardyou decide & act

The gateway step is easy to skip in a tutorial (your ESP32 can talk straight to the cloud) but matters at scale — a real deployment often has dozens of cheap sensors reporting to one gateway that handles the expensive internet connection.

Node 04

The full tech stack

Microcontrollers & SBCs

Arduino Uno/NanoESP32ESP8266Raspberry Pi 4/5STM32Raspberry Pi Pico

Connectivity

Wi-FiBluetooth / BLEZigbeeLoRa / LoRaWANNB-IoT5G / Cellular

Messaging Protocols

MQTTCoAPHTTP/RESTWebSocketsAMQP

Languages

C / C++MicroPythonPythonJavaScript (Node-RED)Rust (embedded)

Cloud & Backend

AWS IoT CoreAzure IoT HubGoogle Cloud IoTThingsBoardFirebase

Data & Dashboards

InfluxDBGrafanaNode-REDTimescaleDBMongoDB

Security

TLS/DTLSX.509 certsSecure bootOTA signingVLAN segmentation
Node 05

Raspberry Pi vs Arduino

The single most common beginner confusion. The short version: Arduino is a microcontroller — it runs one program, close to the hardware, forever, with no operating system. Raspberry Pi is a full computer — it boots Linux, runs multiple programs, and is far more powerful but also far less predictable in timing.

TraitArduino UnoRaspberry Pi 4/5
RunsOne C/C++ program on bare metalFull Linux OS, multitasking
Boot timeInstant, deterministic10–30 seconds
Real-time controlExcellent — precise microsecond timingPoor — OS scheduling adds jitter
Best atReading sensors, driving motors, low powerVision, networking servers, running AI models
Power draw~20–50 mA active~600 mA–1.2 A active
Price (approx.)$5–25$35–80
ARDUINO UNO — sketchUSB-BDC INAREFGND1312~11~10~98A0A1A2A3A4A5Digital pins (top) — amberAnalog pins (bottom) — cyan
RASPBERRY PI — GPIO sketch (first 10 pairs)3V35VGPIO2 (SDA)5VGPIO3 (SCL)GNDGPIO4GPIO14 (TX)GNDGPIO15 (RX)GPIO17GPIO18GPIO27GNDGPIO22GPIO233V3GPIO24GPIO10 (MOSI)GNDPowerGroundGPIO / data
Node 06

Sensors you'll actually use

DHT11 / DHT22

Temperature & humidity

DHT22 is slower but more accurate than DHT11 — pick DHT22 for anything you'd actually publish.

PIR (HC-SR501)

Motion detection

Detects infrared body heat change, not motion itself — a stationary warm object won't re-trigger it.

HC-SR04

Ultrasonic distance

Times an echo pulse; accuracy drops on soft or angled surfaces that absorb or deflect sound.

LDR

Light intensity

A simple voltage-divider resistor — needs a second fixed resistor to produce a readable analog signal.

MQ-2 / MQ-135

Gas & air quality

Needs a 24–48h 'burn-in' and constant heater current — budget for continuous power draw.

Soil Moisture

Irrigation control

Capacitive versions resist corrosion far longer than the cheaper resistive probes.

MPU6050

Accelerometer + gyro

Talks over I2C — remember it needs its own address if you're chaining multiple sensors.

NEO-6M GPS

Location tracking

Needs clear sky view to get a fix; indoors it can take minutes or never lock at all.

LED220Ω resistorBreadboard sketch — LED + resistor
Node 07

How to learn IoT with AI as your lab partner

AI won't solder your board, but it collapses the two slowest parts of learning embedded systems: reading dense datasheets and debugging a circuit you can't see. Use it as a second pair of eyes at every step, not a replacement for actually wiring things up.

  1. 01

    Get one board blinking

    Arduino Uno or ESP32 + the classic blink sketch. This proves your toolchain, drivers, and upload process all work.

    Paste any upload error verbatim into Claude — 90% of first-week bugs are a missing board driver or wrong COM port.

  2. 02

    Read one sensor

    Wire a DHT22 or an LDR and print readings to the Serial Monitor. Learn what 'noisy data' actually looks like.

    Ask AI to explain your sensor's datasheet in plain English — datasheets are dense on purpose, AI compresses them fast.

  3. 03

    Simulate before you solder

    Use Wokwi or Tinkercad Circuits to test wiring and code virtually — no risk of frying a board while learning.

    Describe your circuit in words and ask AI to generate a starting Wokwi diagram.json to skip the blank-canvas problem.

  4. 04

    Talk to the internet

    Publish sensor data over MQTT to a free broker (e.g. HiveMQ public broker) and view it on a simple dashboard.

    Ask AI to write both the publisher firmware AND a matching subscriber script — mismatched topics are the #1 silent failure.

  5. 05

    Add a brain

    Move from 'if sensor > threshold' to a small on-device model (TinyML) or a cloud rule engine for real decisions.

    Ask AI to explain the tradeoff between edge inference (fast, private) and cloud inference (powerful, needs connectivity) for your exact project.

  6. 06

    Build a full loop

    Sensor → microcontroller → broker → database → dashboard → alert. One real end-to-end project teaches more than ten tutorials.

    Have AI review your architecture diagram before you build — catching a design flaw on paper is free; catching it after wiring 12 nodes isn't.

Node 08

Cheat sheets

Protocol comparison

ProtocolTypeRangePowerBest for
MQTTApplication (pub/sub)Internet-wideLowFrequent small telemetry updates to a broker
CoAPApplication (REST-like, UDP)Internet-wideVery lowConstrained devices that can't afford TCP overhead
HTTP/RESTApplication (request/response)Internet-wideHighOne-off requests, firmware downloads, dashboards
BLELink (short range)~10–30 mVery lowWearables, phone-paired sensors
ZigbeeMesh network~10–100 m (mesh extends it)LowSmart home mesh networks (bulbs, switches)
LoRaWANLong-range WAN2–15+ kmVery lowRural sensors sending a few bytes per hour

Arduino sketch skeleton

void setup() {
  Serial.begin(115200);      // debug output
  pinMode(2, INPUT);         // sensor pin
  pinMode(13, OUTPUT);       // actuator / LED
}

void loop() {
  int reading = digitalRead(2);
  if (reading == HIGH) {
    digitalWrite(13, HIGH);  // react to sensor
  } else {
    digitalWrite(13, LOW);
  }
  delay(50);                 // simple debounce
}

MQTT publish / subscribe (Python)

import paho.mqtt.client as mqtt

BROKER, TOPIC = "broker.hivemq.com", "myhome/livingroom/temp"

# --- publisher (on the device) ---
client = mqtt.Client()
client.connect(BROKER, 1883)
client.publish(TOPIC, payload="24.5", qos=1)

# --- subscriber (on the dashboard) ---
def on_message(client, userdata, msg):
    print(msg.topic, msg.payload.decode())

sub = mqtt.Client()
sub.on_message = on_message
sub.connect(BROKER, 1883)
sub.subscribe(TOPIC, qos=1)
sub.loop_forever()

Raspberry Pi GPIO (Python)

from gpiozero import LED, MotionSensor
from time import sleep

led = LED(17)
pir = MotionSensor(4)

while True:
    if pir.motion_detected:
        led.on()
    else:
        led.off()
    sleep(0.1)
Node 09

Important things to keep in mind

3.3V vs 5V is not a suggestion

Feeding a 5V signal into a 3.3V-only pin (most ESP32/Raspberry Pi GPIO) can permanently damage it. Always check the board's logic level before wiring a sensor.

Power budget kills more projects than code bugs

Wi-Fi radios and gas sensors are power-hungry. A battery project that isn't measured in mA-hours on paper first will die in the field within days.

Every internet-connected device is an attack surface

Default passwords and unencrypted MQTT are how IoT botnets happen. Use TLS, unique credentials per device, and sign your OTA updates.

Decide what runs on the edge vs the cloud

Sending raw data to the cloud for every decision adds latency and cost. Time-critical logic (like an emergency shutoff) belongs on the device itself.

Debounce and filter before you trust a reading

A single noisy sensor spike can trigger a false alarm. Average multiple readings or use a debounce window before acting on sensor data.

I2C addresses must be unique on a bus

Two sensors sharing the same default I2C address will collide. Check the datasheet for an address-select pin or use a multiplexer (e.g. TCA9548A).

Node 10

Puzzled? Try these interview questions

These aren't definition-recall questions — they're the kind that expose whether you've actually debugged a circuit at 1am. Tap a question to reveal the answer.

Both devices respond to every read/write meant for 0x68, so their responses collide on the shared SDA line — you get garbled or undefined data, not a clean error. Fix it via an address-select pin, a multiplexer like the TCA9548A, or by putting one sensor on a second I2C bus.

end of transmission - go build something that senses the room it's in.