Why Prompts Matter in IoT and Embedded Development
Building connected devices with Arduino, ESP32, or Raspberry Pi often involves repetitive tasks: reading sensor data, handling MQTT messages, or debugging hardware. Instead of Googling every time, you can use structured prompts to generate code, troubleshoot issues, and design architectures faster. This article collects 15 ready-to-use prompts for real IoT scenarios—from simple sensor polling to automated home systems. Each prompt includes a task description, the exact prompt text, and a code example you can adapt.
Category 1: Basic Prompts for Sensor Reading and Data Logging
1. Read Temperature and Humidity from DHT22 on Arduino
Task: Generate Arduino code to read a DHT22 sensor and print temperature and humidity to the Serial Monitor.
Prompt:
Write an Arduino sketch that:
- Uses the DHT sensor library (version 1.4.4)
- Connects DHT22 data pin to digital pin 2
- Reads temperature in Celsius and humidity every 2 seconds
- Prints values to Serial Monitor with labels
- Handles read errors by printing "Sensor error"
Example Result (Arduino C++):
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
delay(2000);
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Sensor error");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("% Temperature: ");
Serial.print(t);
Serial.println("°C");
}
Explanation: This prompt uses explicit parameters (pin number, library version) and error handling—critical for reliable sensor readings. The DHT22 is accurate to ±0.5°C, making it suitable for environmental monitoring (source: Adafruit DHT22 datasheet).
2. Read Analog Light Sensor on ESP32 and Send to Serial
Task: Generate code for ESP32 to read a photoresistor (LDR) on ADC pin 34 and print the raw value.
Prompt:
Write an ESP32 Arduino core sketch that:
- Reads analog value from GPIO 34 (ADC1 channel 6)
- Converts raw 12-bit value (0-4095) to voltage (0-3.3V)
- Prints both raw value and voltage every 1 second
- Uses analogReadResolution(12)
Example Result:
void setup() {
Serial.begin(115200);
analogReadResolution(12);
}
void loop() {
int raw = analogRead(34);
float voltage = raw * (3.3 / 4095.0);
Serial.print("Raw: ");
Serial.print(raw);
Serial.print(" Voltage: ");
Serial.println(voltage, 3);
delay(1000);
}
Explanation: ESP32 ADC is nonlinear near 0V and 3.3V—for precision, use voltage dividers or external ADC (source: Espressif ESP32 Technical Reference Manual, Chapter 4). This prompt explicitly sets resolution and scales voltage, avoiding common pitfalls.
3. Read Digital Input from Button on Raspberry Pi GPIO
Task: Python script to monitor a push button connected to GPIO 17 on Raspberry Pi with pull-up resistor.
Prompt:
Write a Python script using RPi.GPIO that:
- Sets GPIO 17 as input with pull-up resistor
- Prints "Button pressed" when the pin goes LOW (debounced with 50ms delay)
- Runs until Ctrl+C, then cleans up GPIO
Example Result (Python):
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
try:
while True:
if GPIO.input(17) == GPIO.LOW:
time.sleep(0.05)
if GPIO.input(17) == GPIO.LOW:
print("Button pressed")
while GPIO.input(17) == GPIO.LOW:
time.sleep(0.1)
except KeyboardInterrupt:
GPIO.cleanup()
Explanation: Debouncing prevents false triggers from mechanical bounce. The pull-up resistor ensures a stable HIGH when the button is open. This pattern is standard for any digital input on Raspberry Pi (source: Raspberry Pi Foundation GPIO documentation).
Category 2: Advanced Prompts for MQTT and Wireless Communication
4. ESP32 MQTT Publisher for Temperature and Humidity
Task: Implement a Wi-Fi-connected ESP32 that publishes DHT22 readings to an MQTT broker every 10 seconds.
Prompt:
Write an ESP32 Arduino sketch that:
- Connects to Wi-Fi (SSID and password as constants)
- Connects to MQTT broker at broker.hivemq.com:1883
- Publishes temperature and humidity to topics "home/temperature" and "home/humidity"
- Uses PubSubClient library
- Reconnects if Wi-Fi or MQTT disconnects
- Sends data every 10 seconds
Example Result:
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
const char* ssid = "your_SSID";
const char* password = "your_PASS";
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(2, DHT22);
void setup_wifi() {
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ESP32Client")) {
// success
} else {
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
dht.begin();
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) reconnect();
client.loop();
static unsigned long lastMsg = 0;
if (millis() - lastMsg > 10000) {
lastMsg = millis();
float h = dht.readHumidity();
float t = dht.readTemperature();
if (!isnan(h) && !isnan(t)) {
char tempStr[8];
dtostrf(t, 1, 2, tempStr);
client.publish("home/temperature", tempStr);
char humStr[8];
dtostrf(h, 1, 2, humStr);
client.publish("home/humidity", humStr);
}
}
}
Explanation: MQTT is lightweight and ideal for IoT—HiveMQ's public broker is free for testing. The PubSubClient library handles TCP connections and reconnection logic. This architecture scales to hundreds of sensors (source: HiveMQ MQTT Essentials).
5. Raspberry Pi MQTT Subscriber to Control an LED
Task: Raspberry Pi subscribes to an MQTT topic and turns GPIO 18 LED on/off based on message content.
Prompt:
Write a Python script using paho-mqtt that:
- Connects to broker.hivemq.com
- Subscribes to topic "home/led"
- When message is "ON", sets GPIO 18 HIGH (LED on)
- When message is "OFF", sets GPIO 18 LOW
- Uses RPi.GPIO for output
- Handles reconnection gracefully
Example Result (Python):
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
def on_connect(client, userdata, flags, rc):
client.subscribe("home/led")
def on_message(client, userdata, msg):
if msg.payload == b"ON":
GPIO.output(18, GPIO.HIGH)
elif msg.payload == b"OFF":
GPIO.output(18, GPIO.LOW)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("broker.hivemq.com", 1883, 60)
client.loop_forever()
Explanation: This enables remote control via any MQTT client (e.g., smartphone app). The paho-mqtt library is the standard Python MQTT client (source: Eclipse Paho documentation).
6. ESP32 Deep Sleep with Timer Wake-Up for Battery Life
Task: ESP32 reads a sensor, sends data via MQTT, then goes to deep sleep for 30 minutes to save power.
Prompt:
Write an ESP32 sketch that:
- Connects to Wi-Fi and MQTT
- Reads a DHT22 sensor
- Publishes data to "home/temp"
- Enters deep sleep for 1800 seconds (30 min)
- Uses esp_sleep_enable_timer_wakeup()
- Note: deep sleep does not preserve WiFi connection, so reconnect each cycle
Example Result:
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#define uS_TO_S_FACTOR 1000000
#define TIME_TO_SLEEP 1800
RTC_DATA_ATTR int bootCount = 0;
void setup() {
Serial.begin(115200);
++bootCount;
// Connect Wi-Fi and MQTT, read sensor, publish (code similar to Prompt 4)
// Then:
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
Serial.flush();
esp_deep_sleep_start();
}
void loop() {}
Explanation: Deep sleep reduces ESP32 power consumption to ~10 µA, allowing months on battery (source: Espressif ESP32 Sleep Modes Guide). The RTC_DATA_ATTR preserves boot count across sleep cycles.
Category 3: Expert Prompts for Automation and Complex Systems
7. Multi-Sensor Data Logger to SD Card on Arduino
Task: Log temperature, humidity, and light level to an SD card with timestamps.
Prompt:
Write an Arduino sketch that:
- Uses DHT22 on pin 2, LDR on A0, RTC module DS3231 on I2C
- Writes to SD card (CS pin 10) a CSV file "log.csv"
- Each line: timestamp, temperature, humidity, light (raw)
- Creates file if not exists, appends data every 10 seconds
- Uses SD and RTClib libraries
Example Result:
#include <SD.h>
#include <RTClib.h>
#include <DHT.h>
RTC_DS3231 rtc;
DHT dht(2, DHT22);
File dataFile;
void setup() {
Serial.begin(9600);
if (!rtc.begin()) Serial.println("RTC error");
if (!SD.begin(10)) Serial.println("SD error");
dht.begin();
dataFile = SD.open("log.csv", FILE_WRITE);
if (dataFile) {
dataFile.println("Time,Temp,Humidity,Light");
dataFile.close();
}
}
void loop() {
DateTime now = rtc.now();
float h = dht.readHumidity();
float t = dht.readTemperature();
int light = analogRead(A0);
dataFile = SD.open("log.csv", FILE_WRITE);
if (dataFile) {
char buf[64];
snprintf(buf, 64, "%04d-%02d-%02d %02d:%02d:%02d,%.1f,%.1f,%d",
now.year(), now.month(), now.day(),
now.hour(), now.minute(), now.second(),
t, h, light);
dataFile.println(buf);
dataFile.close();
}
delay(10000);
}
Explanation: SD card logging is essential for offline data collection. The DS3231 RTC maintains accurate time even during power loss (accuracy ±2 ppm, source: Maxim Integrated DS3231 datasheet).
8. OTA (Over-the-Air) Firmware Update for ESP32
Task: Enable OTA updates on ESP32 so you can upload new firmware via Wi-Fi.
Prompt:
Write an ESP32 sketch that:
- Connects to Wi-Fi
- Enables Arduino OTA with password "mysecret"
- Prints IP address to Serial
- Runs LED blink as a background task
- Uses ArduinoOTA library
Example Result:
#include <WiFi.h>
#include <ArduinoOTA.h>
const char* ssid = "your_SSID";
const char* password = "your_PASS";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) delay(500);
ArduinoOTA.setPassword("mysecret");
ArduinoOTA.begin();
pinMode(2, OUTPUT);
}
void loop() {
ArduinoOTA.handle();
digitalWrite(2, !digitalRead(2));
delay(1000);
}
Explanation: OTA eliminates the need for USB cable updates—critical for deployed devices. Always set a password to prevent unauthorized access (source: Arduino ESP32 OTA documentation).
9. Home Automation: ESP32 Controls Relay Based on Temperature Threshold
Task: ESP32 reads temperature and turns on a relay (GPIO 5) if temperature exceeds 30°C, with hysteresis.
Prompt:
Write ESP32 code that:
- Reads DHT22 temperature
- If temperature > 30°C, set relay (GPIO 5) HIGH (fan on)
- If temperature < 28°C, set relay LOW (fan off)
- Publishes state to MQTT topic "home/fan"
- Updates every 5 seconds
Example Result:
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#define RELAY_PIN 5
#define TEMP_ON 30.0
#define TEMP_OFF 28.0
bool fanState = false;
void loop() {
// ... connect Wi-Fi and MQTT as in Prompt 4 ...
float t = dht.readTemperature();
if (t > TEMP_ON && !fanState) {
digitalWrite(RELAY_PIN, HIGH);
fanState = true;
client.publish("home/fan", "ON");
} else if (t < TEMP_OFF && fanState) {
digitalWrite(RELAY_PIN, LOW);
fanState = false;
client.publish("home/fan", "OFF");
}
delay(5000);
}
Explanation: Hysteresis prevents rapid toggling around the threshold. This is standard industrial control practice (source: ISA-88 standard for batch control).
10. Raspberry Pi Camera Module: Capture Image on Motion Detection
Task: Use a PIR motion sensor to trigger the Pi Camera to capture an image and save it with timestamp.
Prompt:
Write a Python script that:
- Uses RPi.GPIO to monitor PIR sensor on GPIO 23
- When motion detected (HIGH), captures an image with picamera
- Saves image as /home/pi/capture_YYYYMMDD_HHMMSS.jpg
- Adds 10-second cooldown to avoid repeated captures
- Runs continuously
Example Result (Python):
import RPi.GPIO as GPIO
import picamera
import time
from datetime import datetime
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN)
camera = picamera.PiCamera()
last_capture = 0
try:
while True:
if GPIO.input(23) == GPIO.HIGH and (time.time() - last_capture) > 10:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"/home/pi/capture_{timestamp}.jpg"
camera.capture(filename)
last_capture = time.time()
except KeyboardInterrupt:
GPIO.cleanup()
Explanation: PIR sensors (like HC-SR501) detect infrared heat changes. Cooldown prevents filling storage with redundant images. The Pi Camera module supports up to 2592×1944 resolution (source: Raspberry Pi Camera Module documentation).
11. ESP32 Web Server for Real-Time Sensor Dashboard
Task: ESP32 hosts a web page showing live sensor data via WebSocket.
Prompt:
Write an ESP32 sketch that:
- Creates a Wi-Fi access point (SSID: "ESP32-Sensor")
- Serves an HTML page with JavaScript that updates temperature and humidity every second
- Uses WebSocket to push data from ESP32 to browser
- Includes the ESPAsyncWebServer and WebSocket libraries
Example Result (simplified):
#include <ESPAsyncWebServer.h>
#include <DHT.h>
AsyncWebServer server(80);
AsyncWebSocket ws("/ws");
DHT dht(2, DHT22);
void setup() {
WiFi.softAP("ESP32-Sensor");
dht.begin();
ws.onEvent(onWsEvent);
server.addHandler(&ws);
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(200, "text/html", webpage);
});
server.begin();
}
void loop() {
ws.cleanupClients();
static unsigned long lastSend = 0;
if (millis() - lastSend > 1000) {
lastSend = millis();
float t = dht.readTemperature();
float h = dht.readHumidity();
char buf[50];
snprintf(buf, 50, "{\"temp\":%.1f,\"hum\":%.1f}", t, h);
ws.textAll(buf);
}
}
Explanation: WebSockets provide low-latency bidirectional communication—ideal for live dashboards. The ESPAsyncWebServer is non-blocking, allowing smooth sensor reads (source: ESPAsyncWebServer GitHub repository).
12. Arduino PID Controller for Temperature Regulation
Task: Implement a PID controller using an Arduino to maintain a setpoint temperature with a heater and DS18B20 sensor.
Prompt:
Write an Arduino sketch that:
- Reads DS18B20 temperature on pin 4 (OneWire)
- Controls a heater on pin 9 via PWM (mosfet)
- Uses PID library to compute output
- Setpoint = 50°C, Kp=10, Ki=0.5, Kd=1
- Prints setpoint, input, output to Serial every second
Example Result:
#include <OneWire.h>
#include <DallasTemperature.h>
#include <PID_v1.h>
OneWire oneWire(4);
DallasTemperature sensors(&oneWire);
double setpoint = 50, input, output;
double Kp = 10, Ki = 0.5, Kd = 1;
PID myPID(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT);
void setup() {
pinMode(9, OUTPUT);
sensors.begin();
myPID.SetMode(AUTOMATIC);
myPID.SetSampleTime(1000);
}
void loop() {
sensors.requestTemperatures();
input = sensors.getTempCByIndex(0);
myPID.Compute();
analogWrite(9, output);
Serial.print("SP:"); Serial.print(setpoint);
Serial.print(" In:"); Serial.print(input);
Serial.print(" Out:"); Serial.println(output);
delay(1000);
}
Explanation: PID control is widely used in industrial automation. Tuning Kp, Ki, Kd requires testing—Ziegler-Nichols method is a common starting point (source: Control System Design by Goodwin et al.).
13. ESP32 MQTT Bridge Between Two Networks
Task: ESP32 reads data from a local sensor and forwards it to a cloud MQTT broker over cellular (SIM800).
Prompt:
Write an ESP32 sketch that:
- Reads DHT22 sensor
- Sends data to a local MQTT broker (192.168.1.100)
- Also sends to a cloud broker (mqtt.eclipseprojects.io) via SIM800 module (SoftwareSerial)
- Uses two PubSubClient instances
Explanation: Bridging allows local control (low latency) and cloud logging. SIM800 modules use AT commands—this adds complexity but enables remote monitoring without Wi-Fi. (Source: SIM800 AT Command Manual).
14. Raspberry Pi as a Bluetooth LE Peripheral for Sensor Data
Task: Raspberry Pi advertises temperature data over BLE so a smartphone can read it.
Prompt:
Write a Python script using bluepy that:
- Creates a BLE peripheral with custom service UUID 1234
- Has a characteristic for temperature (UUID 5678) that returns float value
- Updates value every 5 seconds from a DHT22 connected via GPIO
- Advertises device name "PiTemp"
Explanation: BLE is power-efficient and supported by all modern smartphones. The bluepy library wraps the BlueZ stack (source: bluepy GitHub).
15. Edge AI: ESP32-S3 TensorFlow Lite for Gesture Recognition
Task: Use an accelerometer (ADXL345) to detect a shake gesture and send an MQTT alert.
Prompt:
Write ESP32-S3 code using TensorFlow Lite Micro that:
- Reads ADXL345 acceleration data via I2C
- Runs a pre-trained model (shake detection) on the ESP32
- If confidence > 0.8, publishes "shake_detected" to MQTT topic "home/gesture"
- Uses Arduino_TensorFlowLite_ESP32 library
Explanation: On-device ML reduces latency and cloud dependency. The ESP32-S3 has vector extensions for neural networks (source: Espressif ESP32-S3 Technical Reference Manual).
Conclusion
These 15 prompts cover the spectrum from basic sensor reading to advanced edge AI. Each prompt is designed to be a starting point—modify the parameters, pin numbers, and thresholds to fit your project. The key takeaway: well-structured prompts save hours of debugging and help you focus on the unique aspects of your IoT system. Start with the simple prompts, then combine them into larger automation workflows. For further learning, explore the official documentation of Arduino, ESP32, and Raspberry Pi—they remain the best sources for deep technical details.
Comments