Explore the world of sensors and digital/analog inputs
π From hardware to sensing the world around us
In Lesson 8, you learned the core pattern used in real Arduino projects: read β decide β act. Lesson 9 builds on that by adding new kinds of inputs (digital buttons and analog knobs) and combining them into a single program.
You practiced reading sensor values with analogRead(), comparing them to thresholds, organizing code with functions, and even smoothing readings by taking an average.
Sensors are devices that detect and measure physical properties from the environment and convert them into electrical signals that Arduino can understand. They are the "eyes and ears" of your Arduino projects.
The HC-SR04 measures distance by sending an ultrasonic "ping" and timing how long it takes for the echo to return. Arduino measures that time and converts it into distance.
If you get unstable readings, thatβs normal. Weβll apply Lesson 8 techniques (thresholds and averaging) in the project section.
// HC-SR04 distance reading example
const int trigPin = 9;
const int echoPin = 10;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
float getDistanceCm() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long durationUs = pulseIn(echoPin, HIGH, 30000);
if (durationUs == 0) return -1;
return durationUs * 0.0343f / 2.0f;
}
void loop() {
float d = getDistanceCm();
if (d < 0) {
Serial.println("No echo (out of range)");
} else {
Serial.print("Distance: ");
Serial.print(d);
Serial.println(" cm");
}
delay(100);
} Buttons and switches let the user control your program. In the Lesson 9 project, the button will be used to toggle modes (like enabling/disabling an alarm).
Potentiometers are variable resistors that provide analog input, perfect for controlling brightness, volume, or speed.
// Potentiometer Reading Example
const int potPin = A0; // Potentiometer connected to analog pin A0
const int ledPin = 9; // PWM LED connected to pin 9
int potValue = 0; // Variable to store pot reading
int ledBrightness = 0; // Variable to store LED brightness
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
Serial.println("Potentiometer Control - Turn pot to adjust LED brightness");
}
void loop() {
potValue = analogRead(potPin);
ledBrightness = map(potValue, 0, 1023, 0, 255);
analogWrite(ledPin, ledBrightness);
Serial.print("Pot Value: ");
Serial.print(potValue);
Serial.print(" | LED Brightness: ");
Serial.println(ledBrightness);
delay(100);
} Create a sensor monitoring system that reads multiple input devices and provides real-time feedback through the Serial Monitor.