I need help with my ultrasonic sensor

i want to join my ultrasonic sensor and tilt sensor together like if i click button1 the LCD will display the value of the ultrasonic sensor and if I click button2 it will display the value of tilt sensor. but it only work once like I want to make it work forever until I press the second button to change the sensor here's my code

  #include <LiquidCrystal.h> // Library
  LiquidCrystal lcd(2,3,4,5,6,7);
  const int Button1 = 10;
  const int Button2 = 9;
  #define trigPin A2
  #define echoPin A3
  int Buttonstate1 = 0; 
  int Buttonstate2= 0;
  int BlueLED = A4;
  int BuzzPin = A5;
  int duration, distance;
  int Tilt = analogRead(A1);
  void setup() {
  lcd.begin(16,2);
  pinMode(Button1, OUTPUT);
  pinMode(Button2, OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(BlueLED, OUTPUT);
  pinMode(BuzzPin, OUTPUT);
}
  void loop() {
  float duration, distance;
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * 0.0344;
  Buttonstate1 = digitalRead(Button1);
  Buttonstate2 = digitalRead(Button2);
  if (Buttonstate1 == HIGH) { // Ultrasonic Sensor (Start)
  digitalWrite(BlueLED, HIGH);
  digitalWrite(BuzzPin, HIGH);
  delay(300);
  digitalWrite(BlueLED, LOW);
  digitalWrite(BuzzPin, LOW);
  lcd.clear();
  lcd.print("Distance = ");
  lcd.print(distance);
} // Ultrasonic Sensor (End)

  else if (Buttonstate2 == HIGH) { // Tilt Sensor (Start)
  digitalWrite(BlueLED, HIGH);
  digitalWrite(BuzzPin, HIGH);
  delay(300);
  digitalWrite(BlueLED, LOW);
  digitalWrite(BuzzPin, LOW);
  lcd.clear();
  lcd.print("Tilt = ");
  lcd.print(Tilt);
} // Tilt Sensor (End)
}

What is setting the state of the button pins when the buttons are not pressed ?

Why are your button pins set as outputs ?

what do you mean by that? should I change button pin to Input?

Does a button INPUT something into the sketch or receive OUTPUT from it ?

yeah

"Yeah" is not an answer to the question

Inputs are not outputs.

wait i didnt understand y'all so like my both of buttons are on output right now and both of sensors are in output too..

Always show us a good schematic of your proposed circuit.
Show us a good image of your ‘actual’ wiring.

Hi,
Can you please tell us your electronics, programming, arduino, hardware experience?

Is this all your code?

Did you develop it in stages?
If so do you have code that JUST tests your Buttons?
Do you have code that JUST test the ultrasonics?

Can you please post a circuit diagram of your project?

Thanks.. Tom.. :smiley: :+1: :coffee: :australia: :santa: :santa:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.