Skip to content

Instantly share code, notes, and snippets.

@rburnett3
Created October 15, 2019 13:22
Show Gist options
  • Save rburnett3/e08657b13fec8399e65c907049c569ea to your computer and use it in GitHub Desktop.
Save rburnett3/e08657b13fec8399e65c907049c569ea to your computer and use it in GitHub Desktop.
maxsonar-mb1240-trigger with push button
/* Arduino example code for MaxBotix MB1240 XL-MaxSonar-EZ4 ultrasonic distance sensor with push button. More info: www.makerguides.com */
#define readPin 2
#define triggerPin 3
#define buttonPin 4
long distance = 0;
long duration = 0;
int buttonState = HIGH;
int previous = HIGH;
long time = 0;
long debounce = 200;
void setup() {
pinMode(readPin, INPUT);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(triggerPin, OUTPUT);
digitalWrite(triggerPin, LOW);
Serial.begin(9600);
delay(3000);
Serial.println("Sensor is ready, waiting for button press!");
}
void read_sensor() {
digitalWrite(triggerPin, HIGH);
delayMicroseconds(20);
digitalWrite(triggerPin, LOW);
duration = pulseIn(readPin, HIGH);
distance = duration / 58;
delay(100);
}
void print_data() {
Serial.print("distance = ");
Serial.print(distance);
Serial.println(" cm");
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == LOW && previous == HIGH && millis() - time > debounce) {
read_sensor();
print_data();
time = millis();
}
previous = buttonState;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment