Handout - Sensors - Embedded Programming - ESP32 v1.0
Handout - Sensors - Embedded Programming - ESP32 v1.0
Arduino IDE
#include <HCSR04.h>
UltraSonicDistanceSensor distanceSensor(4, 5);
// Initialize sensor that uses digital pins 4 and 5
void setup () {
Serial.begin(9600);
// We initialize serial connection so that we could print values from sensor.
}
void loop () {
// Every 500 milliseconds, do a measurement using the sensor and print the
//distance in centimetres
Serial.println(distanceSensor.measureDistanceCm());
delay(500);
} • Go to Tools -> Manage libraries
• Search HCSR04 and Install Library of Martin Sosic (Version 2.0.0)
• Open the code File -> Examples -> Example from Custom libraries
-> HCSR04 -> simple
Apr 2025 Copyright © 2021 - 2025 | LEAP | All rights reserved 5
In-class Activity 3 : LDR Detects Light
Code:
const int LDR_Pin = 13; // DO pin connected to digital pin 13
void setup() {
// Initialize serial communication at 9600 baud
Serial.begin(9600);
// Set LDR pin as input
pinMode(LDR_Pin, INPUT);
}
void loop() {
// Read the digital value from the LDR sensor
int LDR_value = digitalRead(LDR_Pin);
if (LDR_value == LOW) {
Serial.println("Bright light detected");
} else {
Serial.println("Low light detected");
}
// Wait 500 milliseconds before reading again
delay(500);
}
Apr 2025 Copyright © 2021 - 2025 | LEAP | All rights reserved 6
In-class Activity 4 : Detects Touch
Code:
const int touchPin = 18; // Pin connected to the touch sensor
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(touchPin, INPUT); // Set touch pin as input
}
void loop() {
int touchValue = digitalRead(touchPin); // Read the state
of the touch sensor
void loop() {
// Read digital data from the sound sensor
int digitalData =
digitalRead(soundSensorPin);
Serial.print("Digital Data: ");
Serial.println(digitalData);