🌡️ Lesson 6: Sensors & Real-World Input
⏱️ Estimated time: 30 minutes | Difficulty: Intermediate
Sensing the World
Sensors allow your Arduino to perceive the world around it — light, temperature, distance, motion, and more.
Temperature Sensor (TMP36)
int tempPin = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int reading = analogRead(tempPin);
float voltage = reading * (5.0 / 1024.0);
float tempC = (voltage - 0.5) * 100.0;
float tempF = tempC * 9.0 / 5.0 + 32.0;
Serial.print("Temperature: ");
Serial.print(tempC);
Serial.println(" °C");
delay(1000);
}
Light Sensor (LDR / Photoresistor)
int ldrPin = A1;
int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
int lightLevel = analogRead(ldrPin);
// Dark = high value → LED brighter
int brightness = map(lightLevel, 0, 1023, 255, 0);
analogWrite(ledPin, brightness);
delay(100);
}
Ultrasonic Distance Sensor (HC-SR04)
int trigPin = 9;
int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// Send pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure echo
long duration = pulseIn(echoPin, HIGH);
float distance = duration * 0.034 / 2; // cm
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500);
}