Sensors
Photoresistor, thermistor, PIR, ultrasonic and DHT22 sensors: how each works and how to read it. Each entry explains what the part does, what it looks like in CircuitBench, how to wire it and, where relevant, an Arduino code example you can paste into the code panel. New to electronics? Start with the electronics basics and the Arduino tutorial.
Photoresistor
SensorWhat it does. A light-dependent resistor: its resistance falls as light increases.
What it looks like. A round face with a wavy track.
How to use it. Pair it with a fixed resistor (about 10 kΩ) as a divider and read the middle point on an analog pin. Move the light slider to test. Which way the numbers move depends on which part is on the 5 V side, so print the values first.
Code example.
int light = analogRead(A0);
if (light < 300) digitalWrite(13, HIGH); // dark: lamp onNTC thermistor
SensorWhat it does. A resistor whose value drops as temperature rises, following a curve set by its R25 and beta values.
What it looks like. A small bead with two leads.
How to use it. Use it in a divider: connect 5 V to a 10 kΩ resistor, then to the thermistor, then to GND, and read the point between them. This code assumes that layout. It converts the reading to degrees with the beta equation.
Code example.
int raw = analogRead(A0);
float r = 10000.0 * raw / (1023.0 - raw);
float tK = 1.0 / (1.0/298.15 + log(r/10000.0)/3950.0);
float tC = tK - 273.15;PIR motion sensor
SensorWhat it does. Detects moving warm bodies and outputs HIGH while it senses motion.
What it looks like. A white dome on a small board with three pins (VCC, OUT, GND).
How to use it. Power it, then read OUT as a digital input.
Code example.
if (digitalRead(4) == HIGH) Serial.println("motion!");HC-SR04 ultrasonic
SensorWhat it does. Measures distance by timing an ultrasonic echo. Range is about 2–400 cm.
What it looks like. Two round “eyes” on a small board with four pins.
How to use it. Send a 10 µs pulse on TRIG, then time the pulse returned on ECHO. Distance in cm = time / 58.
Code example.
digitalWrite(7, LOW); delayMicroseconds(2);
digitalWrite(7, HIGH); delayMicroseconds(10);
digitalWrite(7, LOW);
long t = pulseIn(6, HIGH);
float cm = t / 58.0;DHT22 temp/humidity
SensorWhat it does. A digital sensor giving temperature and humidity over one data wire.
What it looks like. A white grid-faced block with pins.
How to use it. Connect the + leg to 5 V, the − leg to GND and the OUT leg to a board pin (the fourth leg, NC, is not connected to anything). Real modules often add a 10 kΩ pull-up resistor on the data line. Then use the DHT library.
Code example.
#include <DHT.h>
DHT dht(2, DHT22);
void setup(){ Serial.begin(9600); dht.begin(); }
void loop(){
Serial.println(dht.readTemperature());
delay(2000);
}