Created
April 26, 2021 05:31
-
-
Save GluTbl/b57df553e5fb8443512f38dce078fe01 to your computer and use it in GitHub Desktop.
[Ultrasonic distance measurre without delay by using interupts]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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