Sensors and Actuators
Reading temperature, ultrasonic distance, controlling motors and servos with PWM
Skills taught: embedded.sensors
Temperature and Humidity: DHT22
The DHT22 (AM2302) is a popular digital temperature/humidity sensor. It uses a custom single-wire protocol; the DHT library handles all the timing. Accuracy: ±0.5°C temperature, ±2% humidity. It needs at least 2 seconds between readings.
#include <DHT.h>
// Library Manager: search "DHT sensor library" by Adafruit
#define DHT_PIN 4
#define DHT_TYPE DHT22
DHT dht(DHT_PIN, DHT_TYPE);
unsigned long lastRead = 0;
void setup() {
Serial.begin(115200);
dht.begin();
Serial.println(F("DHT22 ready"));
}
void loop() {
if (millis() - lastRead >= 2000) { // 2s minimum interval
lastRead = millis();
float humidity = dht.readHumidity();
float temperature = dht.readTemperature(); // Celsius
float tempF = dht.readTemperature(true); // Fahrenheit
float heatIndex = dht.computeHeatIndex(temperature, humidity, false);
if (isnan(humidity) || isnan(temperature)) {
Serial.println(F("Error: Failed to read DHT22"));
return;
}
Serial.print(F("Temp: ")); Serial.print(temperature, 1); Serial.print(F("°C "));
Serial.print(F("Hum: ")); Serial.print(humidity, 1); Serial.print(F("% "));
Serial.print(F("HeatIdx: ")); Serial.print(heatIndex, 1); Serial.println(F("°C"));
}
}
Distance Measurement: HC-SR04 Ultrasonic
The HC-SR04 measures distance by emitting a 40 kHz ultrasonic pulse and measuring how long the echo takes to return. Range: 2 cm – 400 cm, accuracy ±3 mm. It uses two pins: TRIG (trigger) and ECHO.
#define TRIG_PIN 7
#define ECHO_PIN 8
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
float readDistanceCm() {
// 1. Send 10µs trigger pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// 2. Measure echo pulse width in microseconds
long duration = pulseIn(ECHO_PIN, HIGH, 25000); // 25ms timeout
if (duration == 0) return -1; // timeout = no echo
// 3. Convert: sound travels 343 m/s = 0.0343 cm/µs
// divide by 2 for round trip
return duration * 0.0343 / 2.0;
}
void loop() {
float dist = readDistanceCm();
if (dist < 0) {
Serial.println(F("Out of range"));
} else {
Serial.print(F("Distance: "));
Serial.print(dist, 1);
Serial.println(F(" cm"));
}
delay(100);
}
PWM: Controlling LED Brightness and Servos
PWM (Pulse Width Modulation) simulates analog output by rapidly switching a pin on and off. analogWrite(pin, 0–255) controls the duty cycle. Servo motors use a specific PWM signal: a 50 Hz signal where pulse width (1–2 ms) sets the angle.
#include <Servo.h>
// Servo library is built into Arduino IDE — no install needed
const int SERVO_PIN = 9;
const int POT_PIN = A0; // potentiometer to control servo
Servo myServo;
void setup() {
myServo.attach(SERVO_PIN); // must be a PWM pin
Serial.begin(115200);
}
void loop() {
// Read potentiometer (0–1023) and map to angle (0–180)
int potValue = analogRead(POT_PIN);
int angle = map(potValue, 0, 1023, 0, 180);
myServo.write(angle);
Serial.print(F("Pot: ")); Serial.print(potValue);
Serial.print(F(" Angle: ")); Serial.print(angle); Serial.println(F("°"));
delay(15); // give servo time to move
}
Controlling DC Motors with an H-Bridge
A DC motor draws 100 mA–1 A — far more than a GPIO pin can provide (40 mA max). An H-bridge driver like the L298N or TB6612FNG acts as an amplifier, switching up to 2 A per channel from a motor supply rail while taking logic-level control signals.
// L298N H-Bridge motor driver
// Connect: ENA=PWM pin 9, IN1=pin 7, IN2=pin 6
// Motor A between OUT1 and OUT2
#define ENA 9 // PWM for speed
#define IN1 7
#define IN2 6
void setup() {
pinMode(ENA, OUTPUT);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
}
void motorForward(int speed) { // speed: 0-255
digitalWrite(IN1, HIGH);
digitalWrite(IN2, LOW);
analogWrite(ENA, speed);
}
void motorBackward(int speed) {
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
analogWrite(ENA, speed);
}
void motorStop() {
analogWrite(ENA, 0);
}
void loop() {
motorForward(200); delay(2000); // forward 2s at ~78%
motorStop(); delay(500); // stop
motorBackward(200); delay(2000); // reverse 2s
motorStop(); delay(1000);
}
Warning: Never connect a motor directly to an Arduino GPIO pin. Even small motors can draw 200–500 mA — this will instantly destroy the Arduino's voltage regulator or GPIO protection diodes. Always use a motor driver (L298N, L9110, TB6612FNG) with its own power supply.
DHT11 vs DHT22
- DHT11: Budget temperature/humidity sensor
- DHT22 (AM2302): Higher-accuracy temperature/humidity sensor
Frequently Asked Questions
My DHT22 gives 'nan' readings. What's wrong?
Common causes: (1) reading too fast — wait at least 2 seconds between reads; (2) no pull-up resistor on data pin — add 4.7 kΩ to Vcc; (3) wire too long — keep under 20 cm; (4) power supply noise — add 100 µF capacitor across Vcc and GND.
How do I debounce a button?
Add a 10–20 ms delay after detecting a state change, or use the Bounce2 library. For the millis() approach: record the time of the first edge, ignore further changes for 20 ms, then check the final state.
What is the difference between a servo and a stepper motor?
Servo: continuous rotation (360° DC motor) or limited rotation (hobby servo 0–180°). Easy to control with PWM. Stepper: moves in precise discrete steps (1.8° per step typically). Better for precise positioning (3D printer, CNC). More complex to drive but no feedback needed.