Skip to content

Instantly share code, notes, and snippets.

@jaggzh
Created March 18, 2024 11:56
Show Gist options
  • Save jaggzh/12a8ed8be5d471f208bcba06a7b8984c to your computer and use it in GitHub Desktop.
Save jaggzh/12a8ed8be5d471f208bcba06a7b8984c to your computer and use it in GitHub Desktop.
// Ultrasonic module: HC - SR04
const int US1TRIGPIN = 12;
const int US1ECHOPIN = 13;
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
#define UL unsigned long
#define SUL static unsigned long
#define sp(v) Serial.print(v)
#define spl(v) Serial.println(v)
#define spt(v) do { Serial.print(v); Serial.print("\t"); } while(0)
#define VCNT 10
double vs[VCNT];
int cv=0;
void setup() {
Serial.begin(115200);
delay(1000);
pinMode(US1TRIGPIN, OUTPUT);
pinMode(US1ECHOPIN, INPUT);
for (cv=0; cv<VCNT; cv++) {
vs[cv] = read_us_time_ms(US1TRIGPIN, US1ECHOPIN);
delay(60);
}
}
unsigned long read_us_time_ms(int trigpin, int echopin) {
UL stread=millis(), enread;
UL dur;
/* clear trigger pin */
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
// Reads echo, returns the sound wave travel time in microseconds
dur = pulseIn(echopin, HIGH);
enread=millis();
sp("readms:");
spl(enread-stread);
return dur;
}
double read_us_cm(int trigpin, int echopin) {
return read_us_time_ms(trigpin, echopin) * SOUND_SPEED/2;
}
double vavg() {
double tot=0;
for (int i=0; i<VCNT; i++) tot += vs[i];
return tot/VCNT;
}
void loop() {
static unsigned long last_read_us1_ms=0;
unsigned long cmillis=millis();
if (cmillis-last_read_us1_ms > 1) {
if (++cv >= VCNT) cv=0;
UL newv = read_us_time_ms(US1TRIGPIN, US1ECHOPIN);
last_read_us1_ms = millis();
if (newv > 0) { // if pulseIn() found the pulse
vs[cv] = newv;
}
sp("ms:");
spt(vs[cv]);
sp("avg:");
sp(vavg());
spl("");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment