#include <Ticker.h>
#define debug(str) Serial.println(str)
const int TRIG = 23;
const int ECHO = 22;
Ticker ticks;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(TRIG,OUTPUT);
pinMode(ECHO,INPUT);
ticks.attach(1, timerCallback);
}
void loop() {
// put your main code here, to run repeatedly:
// int d = getDistance();
// debug(d);
// delay(1000); // this speeds up the simulation
}
unsigned int getDistance(void)
{
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting the TRIG_PIN high for 10 microseconds
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
// Read the ECHO_PIN, pulseIn() returns the duration in microseconds
int duration = pulseIn(ECHO, HIGH);
// Calculate the distance:
// Speed of sound is approximately 0.0343 cm/us
// The sound travels to the object and back, so divide by 2
return (duration * 0.0343 / 2);
}
void timerCallback(void)
{
unsigned int dist = getDistance();
debug(dist);
}