Skip to content

Instantly share code, notes, and snippets.

@GluTbl
Created April 26, 2021 05:31
Show Gist options
  • Save GluTbl/b57df553e5fb8443512f38dce078fe01 to your computer and use it in GitHub Desktop.
Save GluTbl/b57df553e5fb8443512f38dce078fe01 to your computer and use it in GitHub Desktop.
[Ultrasonic distance measurre without delay by using interupts]
#include <Arduino.h>
#include <Ticker.h>
#define ULTRASONIC_PIN_INPUT D1
#define ULTRASONIC_PIN_OUTPUT D4
volatile long ultrasonic_echo_start = 0;
volatile long ultrasonic_distance = 0;
Ticker ultrasonic_tick;
void ultrasonicPulse() {
//generate a pulse to activate ultrasonic sensor
digitalWrite(ULTRASONIC_PIN_OUTPUT, HIGH);
delayMicroseconds(10);
digitalWrite(ULTRASONIC_PIN_OUTPUT, LOW);
// record the send time
ultrasonic_echo_start = micros();
}
void ICACHE_RAM_ATTR ultrasonicEcho_falling() {
if (ultrasonic_echo_start != 0) {
int constant_delay = 475;// we have to subtract because it is the time where the echo pin is low after trigger sent.. and it is always constant
ultrasonic_distance = (micros() - ultrasonic_echo_start - constant_delay) / 58;
ultrasonic_echo_start = 0;
}
}
void ultrasnic_setup() {
pinMode(ULTRASONIC_PIN_INPUT, INPUT_PULLUP);
pinMode(ULTRASONIC_PIN_OUTPUT, OUTPUT);
ultrasonic_tick.attach(5, ultrasonicPulse);
attachInterrupt(digitalPinToInterrupt(ULTRASONIC_PIN_INPUT), ultrasonicEcho_falling, FALLING);
}
void setup() {
Serial.begin(115200);
ultrasnic_setup();
}
void loop() {
Serial.print("Distance: ");
Serial.println(ultrasonic_distance);
delay(3000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment