Why Prompts Matter in IoT Development
Building connected devices often involves repetitive tasks—reading sensor data, publishing over MQTT, or handling interrupts. Using structured prompts (templates or code snippets) accelerates prototyping and ensures consistency. Whether you're a hobbyist using Arduino Uno or a professional deploying ESP32-based sensors, these 15 prompts cover the most common scenarios: sensor integration, data logging, wireless communication, and automation.
Each prompt includes a clear description, a code example, and practical notes. Sources are linked to official documentation where possible.
1. Reading a DS18B20 Temperature Sensor on Arduino
Description: Read temperature from a one-wire DS18B20 sensor and print to Serial. Works with any Arduino board.
Prompt code:
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
void setup() {
Serial.begin(9600);
sensors.begin();
}
void loop() {
sensors.requestTemperatures();
float tempC = sensors.getTempCByIndex(0);
if (tempC != DEVICE_DISCONNECTED_C) {
Serial.print("Temperature: ");
Serial.println(tempC);
}
delay(1000);
}
References: OneWire library | DallasTemperature
Practical tip: Use a 4.7kΩ pull-up resistor on the data line; without it, readings will fail.
2. Reading a DHT11/DHT22 Humidity and Temperature Sensor on ESP32
Description: Read humidity and temperature from a DHT sensor on ESP32 using the DHT sensor library.
Prompt code:
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
dht.begin();
}
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.printf("Humidity: %.1f%% Temperature: %.1f°C\n", h, t);
delay(2000);
}
Note: The DHT11 is less accurate (±2°C) than DHT22 (±0.5°C). For ESP32, use delay(2000) minimum.
3. Reading an Analog Sensor (e.g., Potentiometer) on Arduino
Description: Read an analog voltage on pin A0 and map it to a 0-100% scale.
Prompt code:
int sensorPin = A0;
void setup() { Serial.begin(9600); }
void loop() {
int raw = analogRead(sensorPin);
float voltage = raw * (5.0 / 1023.0);
int percent = map(raw, 0, 1023, 0, 100);
Serial.print("Raw: "); Serial.print(raw);
Serial.print(" Voltage: "); Serial.print(voltage);
Serial.print(" V, Percent: "); Serial.println(percent);
delay(500);
}
Reference: Arduino Analog Read
4. Publishing Sensor Data via MQTT on ESP8266/ESP32
Description: Connect to Wi-Fi, then publish temperature and humidity to an MQTT broker (e.g., Mosquitto).
Prompt code:
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected");
}
void reconnect() {
while (!client.connected()) {
if (client.connect("ESP32Client")) {
Serial.println("MQTT connected");
} else {
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) reconnect();
client.loop();
float temperature = 25.3; // replace with actual sensor reading
char msg[50];
snprintf (msg, 50, "{\"temp\":%.1f}", temperature);
client.publish("home/sensor/temperature", msg);
delay(5000);
}
Reference: PubSubClient library | MQTT v3.1.1 spec
Practical tip: Use a local broker like Mosquitto for low-latency; cloud brokers (HiveMQ, AWS IoT) add latency.
5. Subscribing to MQTT Topics on ESP32
Description: Subscribe to a topic and turn on/off an LED based on incoming messages.
Prompt code:
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "...";
const char* password = "...";
const char* mqtt_server = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char* topic, byte* message, unsigned int length) {
String messageTemp;
for (int i = 0; i < length; i++) {
messageTemp += (char)message[i];
}
if (String(topic) == "home/led") {
if (messageTemp == "on") {
digitalWrite(2, HIGH);
} else {
digitalWrite(2, LOW);
}
}
}
void setup() {
pinMode(2, OUTPUT);
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) reconnect();
client.loop();
}
void setup_wifi() { /* same as before */ }
void reconnect() { /* same as before */ }
Reference: MQTT subscribe pattern – PubSubClient examples
6. Reading a Button with Debounce on Arduino
Description: Read a pushbutton with software debounce and toggle an LED.
Prompt code:
const int buttonPin = 2;
const int ledPin = 13;
int ledState = LOW;
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 != lastButtonState) {
if (reading == LOW) {
ledState = !ledState;
digitalWrite(ledPin, ledState);
}
}
}
lastButtonState = reading;
}
Reference: Arduino debounce tutorial
7. Reading a PIR Motion Sensor (HC-SR501) on ESP32
Description: Detect motion and print a message. The sensor output is digital (HIGH when motion).
int pirPin = 15;
int ledPin = 2;
void setup() {
Serial.begin(115200);
pinMode(pirPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
int motion = digitalRead(pirPin);
if (motion == HIGH) {
Serial.println("Motion detected!");
digitalWrite(ledPin, HIGH);
delay(200);
} else {
digitalWrite(ledPin, LOW);
}
delay(100);
}
Note: The HC-SR501 has a warm-up period of 30–60 seconds. Adjust sensitivity and time-delay via potentiometers.
8. Ultrasonic Distance Sensor (HC-SR04) on Arduino
Description: Measure distance in centimeters using ultrasonic echo.
const int trigPin = 9;
const int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
float distance = duration * 0.034 / 2;
Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm");
delay(500);
}
Reference: HC-SR04 datasheet
9. Light Sensor (LDR) with ESP32 – Analog Read and Threshold
Description: Read an LDR (photoresistor) on ADC pin and turn on LED when dark.
int ldrPin = 34; // ADC1_CH6
int ledPin = 2;
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
}
void loop() {
int ldrValue = analogRead(ldrPin);
Serial.println(ldrValue);
if (ldrValue < 1000) { // dark
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
delay(200);
}
Note: ESP32 ADC is non-linear; calibrate using ESP32 ADC calibration.
10. Logging Data to an SD Card on Arduino
Description: Append sensor readings to a file on an SD card module.
#include <SD.h>
#include <SPI.h>
const int chipSelect = 4;
void setup() {
Serial.begin(9600);
if (!SD.begin(chipSelect)) {
Serial.println("SD failed");
return;
}
Serial.println("SD ready");
}
void loop() {
File dataFile = SD.open("datalog.csv", FILE_WRITE);
if (dataFile) {
float temp = 25.4; // placeholder
dataFile.print(millis());
dataFile.print(",");
dataFile.println(temp);
dataFile.close();
}
delay(10000);
}
Reference: SD library
11. Using Deep Sleep on ESP32 to Save Power
Description: Read sensor, publish via MQTT, then deep sleep for 1 hour.
#include <WiFi.h>
#include <PubSubClient.h>
void setup() {
Serial.begin(115200);
// connect WiFi, read sensor, publish
// ... (same as prompt 4)
Serial.println("Going to sleep");
esp_sleep_enable_timer_wakeup(3600 * 1000000); // 1 hour in microseconds
esp_deep_sleep_start();
}
void loop() {} // never reached
Reference: ESP32 Deep Sleep
12. Controlling a Servo Motor with PWM on Raspberry Pi (Python)
Description: Use RPi.GPIO to rotate a servo to 90°.
import RPi.GPIO as GPIO
import time
servo_pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(servo_pin, GPIO.OUT)
pwm = GPIO.PWM(servo_pin, 50) # 50 Hz
pwm.start(0)
def set_angle(angle):
duty = angle / 18 + 2
pwm.ChangeDutyCycle(duty)
time.sleep(1)
set_angle(90)
pwm.stop()
GPIO.cleanup()
Reference: RPi.GPIO documentation | Servo control
13. Reading a BME280 Sensor (I2C) on ESP32
Description: Read temperature, humidity, and pressure via I2C.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
Adafruit_BME280 bme;
void setup() {
Serial.begin(115200);
if (!bme.begin(0x76)) {
Serial.println("BME280 not found");
}
}
void loop() {
Serial.print("Temperature: "); Serial.print(bme.readTemperature());
Serial.print(" °C, Pressure: "); Serial.print(bme.readPressure()/100.0);
Serial.print(" hPa, Humidity: "); Serial.println(bme.readHumidity());
delay(2000);
}
Reference: Adafruit BME280 library
14. Creating a Simple REST API on Raspberry Pi with Flask
Description: Serve sensor data via HTTP GET endpoint.
from flask import Flask, jsonify
import random
app = Flask(__name__)
@app.route('/sensor')
def sensor():
data = {
'temperature': round(random.uniform(20, 30), 1),
'humidity': round(random.uniform(40, 70), 1)
}
return jsonify(data)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
Reference: Flask documentation
15. OTA (Over-the-Air) Update on ESP32
Description: Upload new firmware wirelessly using Arduino IDE OTA.
#include <WiFi.h>
#include <ArduinoOTA.h>
const char* ssid = "...";
const char* password = "...";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
delay(5000);
ESP.restart();
}
ArduinoOTA.begin();
}
void loop() {
ArduinoOTA.handle();
}
Reference: ArduinoOTA library – part of ESP32 core.
Conclusion
These 15 prompts cover the essential building blocks of IoT and embedded projects: from sensor reading to wireless communication and power management. Bookmark this guide, adapt the code to your specific hardware, and combine prompts to build robust, real-world systems. For deeper learning, refer to the official libraries and datasheets linked in each prompt. Happy making!
Comments