Introduction
The Internet of Things (IoT) has moved from a futuristic concept to an everyday reality, powering smart homes, industrial automation, and environmental monitoring. Whether you're a hobbyist tinkering with an Arduino Uno, a maker building a connected weather station with an ESP32, or a professional deploying a Raspberry Pi-based edge server, the key to success lies in how effectively you interact with your hardware. Prompts—structured instructions or queries—can dramatically speed up development, debugging, and data analysis. This article presents 18 carefully curated prompts organized into basic, advanced, and expert categories. Each prompt includes a clear task, the exact prompt text, and a real-world example with code. By the end, you'll have a reusable toolkit to accelerate your IoT projects, from reading a simple temperature sensor to implementing MQTT-based automation with cloud integration. Let's dive in.
Basic Prompts (6 prompts)
1. Prompt: Read Temperature and Humidity from DHT22
Task: Get a formatted reading from a DHT22 sensor connected to an Arduino.
Prompt: "Write an Arduino sketch that reads temperature (in Celsius) and humidity from a DHT22 sensor connected to digital pin 2. Print the values to the Serial Monitor every 2 seconds. Include error handling for sensor read failures."
Example Result:
#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("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("% Temperature: ");
Serial.print(t);
Serial.println("°C");
}
Explanation: This prompt produces a complete, production-ready sketch. The DHT22 is a common sensor (datasheet: Adafruit DHT22). The prompt specifies pin, interval, and error handling, saving you from writing boilerplate.
2. Prompt: Blink an LED with PWM
Task: Create a breathing LED effect using PWM on an Arduino.
Prompt: "Generate an Arduino sketch that fades an LED connected to pin 9 (PWM-capable) from off to fully bright and back, with a 3-second cycle. Use analogWrite()."
Example Result:
int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
for (int brightness = 0; brightness <= 255; brightness++) {
analogWrite(ledPin, brightness);
delay(6); // ~1.5s to go up
}
for (int brightness = 255; brightness >= 0; brightness--) {
analogWrite(ledPin, brightness);
delay(6);
}
}
Explanation: PWM (Pulse Width Modulation) is fundamental for controlling brightness. The prompt yields a smooth fade. Adjust delay for speed.
3. Prompt: Measure Distance with HC-SR04
Task: Read distance from an ultrasonic sensor.
Prompt: "Write an Arduino sketch that measures distance using an HC-SR04 ultrasonic sensor. Trigger pin = 10, Echo pin = 11. Print distance in centimeters to Serial Monitor. Average 5 readings to reduce noise."
Example Result:
#define TRIG 10
#define ECHO 11
void setup() {
Serial.begin(9600);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
}
long readDistance() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long duration = pulseIn(ECHO, HIGH);
return duration * 0.034 / 2;
}
void loop() {
long sum = 0;
for (int i = 0; i < 5; i++) {
sum += readDistance();
delay(50);
}
Serial.print("Distance: ");
Serial.print(sum / 5);
Serial.println(" cm");
delay(1000);
}
Explanation: Averaging reduces jitter. The HC-SR04 is widely used in robotics (see HC-SR04 datasheet). The prompt assumes you need clean data.
4. Prompt: Toggle an LED with a Button
Task: Debounce a button to toggle an LED.
Prompt: "Write an Arduino sketch that toggles an LED on pin 13 each time a button connected to pin 2 is pressed. Implement software debounce with a 50ms delay. Use pull-up resistor internally."
Example Result:
const int buttonPin = 2;
const int ledPin = 13;
int ledState = LOW;
int buttonState;
int lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
}
void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == LOW) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
}
}
}
lastButtonState = reading;
}
Explanation: Debouncing is critical for reliable input. This prompt uses INPUT_PULLUP, avoiding external resistors.
5. Prompt: Read Analog Light Sensor
Task: Get light level from an LDR.
Prompt: "Write an Arduino sketch that reads an analog light-dependent resistor (LDR) on A0. Print raw analog value (0-1023) and map it to a percentage (0-100%). Update every second."
Example Result:
int ldrPin = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = analogRead(ldrPin);
int percent = map(raw, 0, 1023, 0, 100);
Serial.print("Raw: ");
Serial.print(raw);
Serial.print(" | Light: ");
Serial.print(percent);
Serial.println("%");
delay(1000);
}
Explanation: LDRs are simple analog sensors. Mapping gives a human-readable percentage. Calibration may be needed for absolute lux.
6. Prompt: Control Servo Motor
Task: Sweep a servo motor back and forth.
Prompt: "Write an Arduino sketch that sweeps a servo motor connected to pin 9 from 0 to 180 degrees and back, in 1-degree steps with 15ms delay per step. Use the Servo library."
Example Result:
#include <Servo.h>
Servo myservo;
int pos = 0;
void setup() {
myservo.attach(9);
}
void loop() {
for (pos = 0; pos <= 180; pos++) {
myservo.write(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos--) {
myservo.write(pos);
delay(15);
}
}
Explanation: Servos are common in robotics. The Servo library handles PWM generation. Delay controls speed.
Advanced Prompts (6 prompts)
7. Prompt: ESP32 Wi-Fi Scan
Task: List available Wi-Fi networks via Serial.
Prompt: "Write an ESP32 Arduino sketch that scans for Wi-Fi networks and prints SSID, signal strength (RSSI), and encryption type to Serial. Scan every 10 seconds."
Example Result:
#include <WiFi.h>
void setup() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
}
void loop() {
int n = WiFi.scanNetworks();
Serial.println("Scan done");
if (n == 0) {
Serial.println("No networks found");
} else {
for (int i = 0; i < n; i++) {
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(") ");
Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN)?"open":"secured");
}
}
delay(10000);
}
Explanation: This prompt is perfect for site surveys. The ESP32's Wi-Fi capabilities are documented in Espressif's ESP-IDF guide.
8. Prompt: MQTT Publish Sensor Data
Task: Send temperature from ESP32 to an MQTT broker.
Prompt: "Write an ESP32 sketch that connects to Wi-Fi (SSID 'MyWiFi', password 'pass123'), then publishes temperature from a DHT22 to MQTT topic 'home/sensor/temp' on broker test.mosquitto.org port 1883 every 5 seconds. Use PubSubClient library."
Example Result:
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
#define WIFI_SSID "MyWiFi"
#define WIFI_PASS "pass123"
#define MQTT_SERVER "test.mosquitto.org"
#define MQTT_TOPIC "home/sensor/temp"
WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(2, DHT22);
void setup() {
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
client.setServer(MQTT_SERVER, 1883);
dht.begin();
}
void loop() {
if (!client.connected()) {
client.connect("ESP32Client");
}
client.loop();
float t = dht.readTemperature();
if (!isnan(t)) {
char msg[8];
dtostrf(t, 1, 2, msg);
client.publish(MQTT_TOPIC, msg);
}
delay(5000);
}
Explanation: MQTT is the standard IoT messaging protocol. This prompt uses a public broker (test.mosquitto.org) for testing. For production, use a secure broker.
9. Prompt: ESP32 Deep Sleep with Timer Wake
Task: Save power by sleeping between measurements.
Prompt: "Write an ESP32 sketch that reads a DHT22, publishes to MQTT, then enters deep sleep for 10 minutes. Use timer wake-up. Print wake-up reason."
Example Result:
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
RTC_DATA_ATTR int bootCount = 0;
void setup() {
Serial.begin(115200);
bootCount++;
Serial.println("Boot number: " + String(bootCount));
// Wi-Fi and MQTT code (same as previous)
// ...
esp_sleep_enable_timer_wakeup(10 * 60 * 1000000); // 10 minutes
Serial.println("Going to sleep now");
esp_deep_sleep_start();
}
void loop() {} // Not used
Explanation: Deep sleep is crucial for battery-powered projects. The RTC_DATA_ATTR retains boot count. Espressif's deep sleep documentation provides more options.
10. Prompt: Raspberry Pi I2C Read from Sensor
Task: Read temperature from an SHT31 sensor via I2C on Raspberry Pi.
Prompt: "Write a Python script for Raspberry Pi that reads temperature and humidity from an SHT31 sensor (I2C address 0x44). Use the smbus2 library. Print values every 2 seconds."
Example Result:
import smbus2
import time
bus = smbus2.SMBus(1)
address = 0x44
def read_sht31():
bus.write_i2c_block_data(address, 0x2C, [0x06])
time.sleep(0.5)
data = bus.read_i2c_block_data(address, 0x00, 6)
temp_raw = (data[0] << 8) | data[1]
temp = -45 + 175 * (temp_raw / 65535.0)
hum_raw = (data[3] << 8) | data[4]
hum = 100 * (hum_raw / 65535.0)
return temp, hum
while True:
t, h = read_sht31()
print(f"Temp: {t:.2f}°C, Humidity: {h:.2f}%")
time.sleep(2)
Explanation: The SHT31 is a precision sensor. The smbus2 library is standard for I2C on Raspberry Pi. See the SHT31 datasheet for command details.
11. Prompt: Raspberry Pi GPIO Input with Interrupt
Task: Detect button press using edge detection.
Prompt: "Write a Python script for Raspberry Pi that uses GPIO.add_event_detect to detect a falling edge on pin 17 (with pull-up). Print 'Button pressed' and debounce for 200ms."
Example Result:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
def button_callback(channel):
print("Button pressed")
GPIO.add_event_detect(17, GPIO.FALLING, callback=button_callback, bouncetime=200)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()
Explanation: Interrupts are more efficient than polling. The bouncetime parameter handles debounce.
12. Prompt: Raspberry Pi Camera Capture
Task: Capture an image with the Pi Camera module.
Prompt: "Write a Python script that captures a JPEG image with the Raspberry Pi Camera Module v2, resolution 1920x1080, saves it as 'photo.jpg', and prints 'Image saved'."
Example Result:
from picamera import PiCamera
from time import sleep
camera = PiCamera()
camera.resolution = (1920, 1080)
camera.start_preview()
sleep(2) # Allow sensor to adjust
camera.capture('photo.jpg')
camera.stop_preview()
print("Image saved")
Explanation: The PiCamera library is specific to Raspberry Pi. The preview delay ensures proper exposure.
Expert Prompts (6 prompts)
13. Prompt: ESP32 OTA Firmware Update
Task: Enable over-the-air updates for an ESP32.
Prompt: "Write an ESP32 sketch that connects to Wi-Fi and enables Arduino OTA. Include a web server that shows firmware version. Use AsyncElegantOTA library."
Example Result:
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <AsyncElegantOTA.h>
const char* ssid = "MyWiFi";
const char* password = "pass123";
AsyncWebServer server(80);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting...");
}
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(200, "text/plain", "Firmware v1.0");
});
AsyncElegantOTA.begin(&server);
server.begin();
Serial.println("OTA ready at " + WiFi.localIP().toString());
}
void loop() {
AsyncElegantOTA.loop();
}
Explanation: OTA updates are essential for deployed devices. AsyncElegantOTA provides a web interface. See Espressif's OTA documentation.
14. Prompt: ESP32 Bluetooth LE Beacon
Task: Broadcast an iBeacon-compatible BLE signal.
Prompt: "Write an ESP32 sketch that advertises as an iBeacon with UUID 12345678-1234-1234-1234-123456789012, major 1, minor 1, TX power -59 dBm. Use the ESP32 BLE library."
Example Result:
#include <BLEDevice.h>
#include <BLEBeacon.h>
void setup() {
BLEDevice::init("ESP32_BEACON");
BLEBeacon beacon;
beacon.setManufacturerId(0x004C); // Apple
beacon.setProximityUUID(BLEUUID("12345678-1234-1234-1234-123456789012"));
beacon.setMajor(1);
beacon.setMinor(1);
beacon.setSignalPower(-59);
BLEAdvertising *advertising = BLEDevice::getAdvertising();
advertising->setAdvertisementData(beacon.getBeacon());
advertising->start();
}
void loop() { delay(1000); }
Explanation: BLE beacons are used for proximity detection. The iBeacon format is defined by Apple. This prompt creates a standalone beacon.
15. Prompt: Raspberry Pi MQTT Broker
Task: Run a local MQTT broker on Raspberry Pi.
Prompt: "Write a bash script that installs and starts the Mosquitto MQTT broker on a Raspberry Pi, configures it for local connections only (port 1883), and enables it on boot. Include a test subscribe command."
Example Result:
#!/bin/bash
sudo apt update
sudo apt install -y mosquitto mosquitto-clients
sudo systemctl enable mosquitto
sudo systemctl start mosquitto
# Test: subscribe in a separate terminal
# mosquitto_sub -h localhost -t "test/topic"
Explanation: Mosquitto is the leading open-source MQTT broker. This script sets up a local broker for development. Official documentation at mosquitto.org.
16. Prompt: ESP32 Web Server with REST API
Task: Control an LED via HTTP POST.
Prompt: "Write an ESP32 sketch that creates a web server with a REST endpoint POST /led that accepts JSON {"state":"on"} or {"state":"off"} to control GPIO 2. Return 200 on success, 400 on invalid data."
Example Result:
#include <WiFi.h>
#include <ArduinoJson.h>
#include <WebServer.h>
WebServer server(80);
const int ledPin = 2;
void handleLed() {
if (server.hasArg("plain") == false) {
server.send(400, "text/plain", "Body not received");
return;
}
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, server.arg("plain"));
if (error) {
server.send(400, "text/plain", "Invalid JSON");
return;
}
const char* state = doc["state"];
if (strcmp(state, "on") == 0) {
digitalWrite(ledPin, HIGH);
server.send(200, "text/plain", "LED on");
} else if (strcmp(state, "off") == 0) {
digitalWrite(ledPin, LOW);
server.send(200, "text/plain", "LED off");
} else {
server.send(400, "text/plain", "Invalid state");
}
}
void setup() {
pinMode(ledPin, OUTPUT);
WiFi.begin("SSID", "PASS");
server.on("/led", HTTP_POST, handleLed);
server.begin();
}
void loop() { server.handleClient(); }
Explanation: RESTful APIs enable integration with web dashboards. ArduinoJson is the standard JSON library.
17. Prompt: Edge ML with TensorFlow Lite on Raspberry Pi
Task: Run a pre-trained TensorFlow Lite model for object detection.
Prompt: "Write a Python script that loads a TensorFlow Lite model (mobilenet_ssd_v2) and runs inference on a captured image from the Pi Camera. Print detected objects with confidence > 0.5."
Example Result:
import tflite_runtime.interpreter as tflite
import numpy as np
from PIL import Image
interpreter = tflite.Interpreter(model_path="detect.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
image = Image.open("photo.jpg").resize((300, 300))
input_data = np.expand_dims(np.array(image, dtype=np.uint8), 0)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
boxes = interpreter.get_tensor(output_details[0]['index'])
classes = interpreter.get_tensor(output_details[1]['index'])
scores = interpreter.get_tensor(output_details[2]['index'])
for i in range(len(scores[0])):
if scores[0][i] > 0.5:
print(f"Detected class {int(classes[0][i])} with confidence {scores[0][i]}")
Explanation: TensorFlow Lite enables on-device ML. This example uses a common object detection model. See TensorFlow Lite documentation for model conversion.
18. Prompt: LoRaWAN Data Transmission with ESP32
Task: Send sensor data over LoRaWAN using a LoRa module.
Prompt: "Write an ESP32 sketch that uses a LoRa module (e.g., RFM95) and the MCCI LoRaWAN library to join The Things Network (TTN) via OTAA, then sends temperature and humidity every hour. Use deep sleep between transmissions."
Example Result:
#include <lmic.h>
#include <hal/hal.h>
#include <DHT.h>
// OTAA keys (from TTN)
static const u1_t PROGMEM APPEUI[8] = { ... };
void os_getArtEui (u1_t* buf) { memcpy_P(buf, APPEUI, 8); }
static const u1_t PROGMEM DEVEUI[8] = { ... };
void os_getDevEui (u1_t* buf) { memcpy_P(buf, DEVEUI, 8); }
static const u1_t PROGMEM APPKEY[16] = { ... };
void os_getDevKey (u1_t* buf) { memcpy_P(buf, APPKEY, 16); }
DHT dht(2, DHT22);
void do_send(osjob_t* j) {
float t = dht.readTemperature();
float h = dht.readHumidity();
if (!isnan(t) && !isnan(h)) {
uint8_t payload[4];
payload[0] = (int)(t * 10);
payload[1] = (int)(h * 10);
LMIC_setTxData2(1, payload, sizeof(payload), 0);
}
}
void onEvent (ev_t ev) {
if (ev == EV_TXCOMPLETE) {
esp_sleep_enable_timer_wakeup(3600 * 1000000); // 1 hour
esp_deep_sleep_start();
}
}
void setup() {
dht.begin();
LMIC_setClockError(MAX_CLOCK_ERROR * 1 / 100);
LMIC_startJoining();
}
void loop() { os_runloop_once(); }
Explanation: LoRaWAN is ideal for long-range, low-power IoT. This prompt integrates deep sleep for battery life. See The Things Network documentation for key provisioning.
Conclusion
These 18 prompts cover the full spectrum of IoT and embedded development, from basic sensor reading to advanced LoRaWAN and edge ML. By using prompts as structured starting points, you can reduce development time and avoid common pitfalls. Remember to adapt the code to your specific hardware and environment—always verify pin assignments, library versions, and network credentials. As you gain confidence, modify these prompts to create your own custom solutions. The IoT ecosystem is vast, but with the right prompts, you can build reliable, scalable devices. Start with a simple temperature monitor, then move to MQTT and cloud integration. The journey from blinking an LED to deploying a LoRaWAN sensor network is just a few prompts away. Happy making!
Comments