Ultrasonic sensor with LED, how can I do this?

Not sure you'd get the behavior you want from that code.

How about this?

// in setup create 
bool pressed = false;

// in loop
void loop {
  distance = readultrasonic();
  pressed = readbutton();
  if distance < 10 {
    if (pressed) {
      buzz(3);
      pressed=false;
    }
    updateLEDS();
  }
}

int readultrasonic() {
  // your read from the ultrasonic sensor goes here
  // always returns an integer, whether the sensor yields one or not
  // if the sensor yields a non-integer result because nearest object is out of range
  // of detection, then return 11 (so the LEDs and buzzer won't trigger).
}

bool readbutton() {
  // your button checking code goes here
  // always returns false unless button is pressed
}

void updateLEDS() {
  // your LED toggling code goes here
}

void buzz(int numbuzzes) {
  // loop and buzz as many times as indicated by numbuzzes value

  // if you want to up your game, test for a button press after every buzz
}
1 Like