// The pin numbers for the ultrasonic sensor's trigger and echo pins
const byte trigpin = 13;
const byte echopin = 12;
// An array of pin numbers for the LEDs
const byte ledpins[] = {11, 10, 9, 8};
// The wait time in seconds between each loop iteration
const float loop_wait_s = 0.1;
// Variables for storing measured distance and number of leds that need to be on
int distance;
byte onleds;
// Determine the wait time in milliseconds for use in delay
const unsigned long loop_wait_ms = loop_wait_s * 1000UL;
// Determine the total number of LEDs based on the array size
const byte numleds = sizeof(ledpins) / sizeof(byte);
// Setup
void setup() {
// Begin serial communication at 9600 baud
Serial.begin(9600);
// Set the ultrasonic sensor pins
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
// Set each LED pin
for (int i = 0; i < numleds; i++) {
pinMode(ledpins[i], OUTPUT);
}
}
// Send a trigger pulse for the ultrasonic sensor
// Code from Arduino lessons
void trigger() {
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
}
// Loop
void loop() {
// Trigger the ultrasonic sensor for distance measurement
trigger();
// Determine the distance based on the pulse duration received at the echo pin
distance = floor((pulseIn(echopin, HIGH) * 0.0343) / 2);
// Determine the number of leds to turn on based on distance
onleds = distance / 100;
// Update the leds based on the determined onleds value
for (int i = 0; i < numleds; i++) {
digitalWrite(ledpins[i], i < onleds ? HIGH : LOW);
}
// Delay to wait before starting the next loop
delay(loop_wait_ms);
}