Working with Sensors
Sensors give your robot the ability to sense the world around it.
Digital vs Analog Sensors
- Digital: Returns ON/OFF (HIGH/LOW) - Example: Push button, IR obstacle sensor
- Analog: Returns range of values (0-1023) - Example: Temperature sensor, potentiometer
Example 1: Push Button
const int buttonPin = 2;
const int ledPin = 13;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
int buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH); // Turn LED on
} else {
digitalWrite(ledPin, LOW); // Turn LED off
}
}
Example 2: Ultrasonic Distance Sensor (HC-SR04)
const int trigPin = 9;
const int echoPin = 10;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
// Send ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure echo time
long duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
float distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(500);
}
Example 3: Analog Temperature Sensor (LM35)
const int tempPin = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(tempPin);
// Convert to voltage (5V reference)
float voltage = sensorValue * (5.0 / 1023.0);
// Convert to Celsius (LM35: 10mV per degree)
float temperature = voltage * 100;
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
delay(1000);
}
Practice: Try connecting multiple sensors and displaying their values on Serial Monitor!