Doing Things Proper

I made a proximity sensor with lights and sound. But being self taught, was wondering if an " else" funtion to keep lights and sound off is a better option?

const int trigPin = 9;
const int echoPin = 10;
const int buzzerPin = 3;
const int ledPin1 = 5;
const int ledPin2 = 6;


long duration;
float distanceInches;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    
}

void loop() {
  // Clear the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Send 10 µs pulse to trigger
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read echo time
  duration = pulseIn(echoPin, HIGH);

  // Convert to inches
  distanceInches = duration * 0.0133 / 2;

  // Print to Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distanceInches);
  Serial.println(" inches");

  delay(250);
    
 if(distanceInches < 4) {
        tone(buzzerPin, 1000);
        digitalWrite(ledPin1, HIGH);
        delay(100);
        tone(buzzerPin, 1500);
        digitalWrite(ledPin2, HIGH);
        delay(100);
        noTone(buzzerPin);
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        delay(400);
    }   
    
}
  • Always show us a good schematic of your proposed circuit. Show us good images of your ‘actual’ wiring.

/*
 * Ultrasonic Distance Alarm
 * Detects objects within 4 inches and triggers a two-tone alarm with LEDs.
 */

const int trigPin = 9;
const int echoPin = 10;
const int buzzerPin = 3;
const int ledPin1 = 5;
const int ledPin2 = 6;

long duration;
float distanceInches;

void setup() {
  // Initialize Serial communication
  Serial.begin(9600);
  
  // Define pin modes
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

void loop() {
  // Clear the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Send 10 microsecond pulse to trigger the sensor
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echo time (duration of the travel in microseconds)
  duration = pulseIn(echoPin, HIGH);

  // Convert time to inches
  // Calculation: (Speed of Sound is ~13,500 inches/sec) / 2 for round trip
  distanceInches = duration * 0.0133 / 2;

  // Debugging output to Serial Monitor
  Serial.print("Distance: ");
  if (duration == 0) {
    Serial.println("Out of range");
  } else {
    Serial.print(distanceInches);
    Serial.println(" inches");
  }

  // Alarm Logic
  // distanceInches > 0 ensures we don't trigger on a sensor timeout
  if (distanceInches > 0 && distanceInches < 4) {
    // Stage 1: First tone and LED
    tone(buzzerPin, 1000);
    digitalWrite(ledPin1, HIGH);
    delay(100);

    // Stage 2: Second tone and LED
    tone(buzzerPin, 1500);
    digitalWrite(ledPin2, HIGH);
    delay(100);

    // Turn off feedback
    noTone(buzzerPin);
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    
    // Short pause to keep the alarm "pulsing"
    delay(200); 
  } else {
    // Standard delay between readings when no object is close
    delay(250);
  }
}

  • Is this a passive buzzer ?
  • Does the LED have a current limiting resistor ?

Edit

You may want to extend the delay:

delay(100);

    tone(buzzerPin, 1000);
    digitalWrite(ledPin1, HIGH);
    delay(1000);  // <——-<<<<

Been programming for over 65 years, never heard of an else 'function'.

Are you sure you want the conversion inherent in that statement
and this one

Im a self taught noob lol. I think i ment else as a " command" not function. Still learning proper terms when disecting code. Aint got no one to teach me , but by golly im trying. Lol

I get what your saying aout explaining my work and ill start doing that better. But that code is soo simple ,i didnt feel the need. U a smart dude! I wanna be like Larry. I do have the the book "Algorithms and data structures equal programs on the way. Supposed to be a good one. Thanx!

Not a command either. May I suggest reading cover to cover 'The C Programming Language'. Then for Arduino specifics, the Arduino Cookbook.

Actually it's Data Structures and Algorithms but yes it is a good intermediate to advanced book. You need to start at the beginning so you know what 'else' is etc.

Would you describe how you intend the devices in this project to function, especially the lights and sound. Is the proximity sensor stationary or moving?

code looks good, clean to me

i wonder if what you're really asking if there is a way to maintain an active indication as long as the distance < 4 and only turn it off when distance >= 4?


bool active = false;

void check (
    int distance )
{
    if (! active && 4 > distance)  {
        active = true;
        turnOn ();
    }
    else if (active && 4 < distance)  {
        active = false;
        turnOff ();
    }
}

You can also start here, if you need baby steps:
https://docs.arduino.cc/language-reference/

Those Arduino Reference pages provide only a subset of the full language features, which is actually a blessing for many. While browsing it, you can be waiting for the recommended reading to arrive, presuming you've ordered it.

The C Programming Language provides a complete description of "C" and small programs demonstrating its features

Has anyone answered your question or do you still need help?
I don't need a schematic and I understand what you mean even though your terminology is not according to C specifications.

That's quite an astute observation, indeed.

@squishyjiggles
Just ask

Thanks for thr reply Jim. No, no one really seemed to get my question. But many did recomend some good reading material to check out. Was just just wondering if at the very end of my code- after the "if" , should i use an "else" with the commands in those curly brackets to keep sound and visuals off. Amature trying to look more professional, i guess

Well, in your setup() you should initialize any outputs to a known state, so set the LEDs to LOW and do a noTone. Now when the program starts the LEDs will be off and there will not be a tone unless you do otherwise.

Since in your if statement you do turn the LEDs off and do a noTone, putting it again in an else would be superfluous. Also, the compiler may see that it’s already been done and actually optimize out the else statement altogether.

when the proximity detector recognizes an object within the distance threshold, this code causes the tones to repeatedly cycle on and off as long the the object remains within the distance threshold, as well as to complete the cycle when an object goes outside of the distance threshold, not terminate immediately

?

The information you provide directly effects the help you receive.

do you understand the above code?