/*
Arduino | coding-help
swordofstyx Sunday, March 15, 2026 5:10 PM
I am working on a personal project and need my sonic sensor to be
used in if/else statements and i am having trouble finding the
proper code. I want it so if something is 12 inches away it reacts
causes the if statement to occour if that makes sense
*/
#include <LiquidCrystal.h>
const int RS = 12, EN = 11, D4 = 10, D5 = 9, D6 = 8, D7 = 7;
const int LED_PINS[] = {6, 5, 4};
const int TRIG_PIN = 3;
const int ECHO_PIN = 2;
const int MODE_PIN = 14;
bool mode = true;
LiquidCrystal lcd (RS, EN, D4, D5, D6, D7);
int getDistance() { // in inches
float distance = 0.0;
// send trigger
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// calculate distance
unsigned long duration = pulseIn(ECHO_PIN, HIGH);
if (mode) {
distance = (duration * 0.0343) / 2; // cm
} else {
distance = (duration * 0.0135) / 2; // inch
}
// return distance as an integer
return (int)(distance + 0.5);
}
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
for (int i = 0; i < 3; i++) {
pinMode(LED_PINS[i], OUTPUT);
}
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(MODE_PIN, INPUT_PULLUP);
lcd.setCursor(3, 0);
lcd.print("Distance:");
}
void loop() {
char buffer[16];
// get mode
mode = digitalRead(MODE_PIN);
// get distance
int distance = getDistance();
// show distance on lcd
snprintf(buffer, 16, "%3d %s", distance, mode ? "cm" : "in");
lcd.setCursor(4, 1);
lcd.print(buffer);
// turn all LEDs off
for (int i = 0; i < 3; i++) {
digitalWrite(LED_PINS[i], LOW);
}
// turn on correct LED
if (distance <= (mode ? 30 : 12)) {
digitalWrite(LED_PINS[0], HIGH);
}
else if (distance <= (mode ? 61 : 24)) {
digitalWrite(LED_PINS[1], HIGH);
}
else if (distance <= (mode ? 91 : 36)) {
digitalWrite(LED_PINS[2], HIGH);
} else {
// > 36" code
}
// slow down the readings
delay(1000);
}
CM <> IN