Skip to content

Instantly share code, notes, and snippets.

@hollyhockberry
Created June 21, 2022 11:36
Show Gist options
  • Save hollyhockberry/d2d4cd8cc00b6e547972e6bf9d490a7a to your computer and use it in GitHub Desktop.
Save hollyhockberry/d2d4cd8cc00b6e547972e6bf9d490a7a to your computer and use it in GitHub Desktop.
M5Stack: UNIT ULTRASONIC-I2C
#include <Arduino.h>
#include <Wire.h>
float read_distance() {
Wire.beginTransmission(0x57);
Wire.write(0x01);
Wire.endTransmission();
::delay(50);
if (Wire.requestFrom(0x57, 3) != 3) {
return -1;
}
uint32_t data = Wire.read();
data = (data << 8) | Wire.read();
data = (data << 8) | Wire.read();
return data / 1000.f;
}
void setup() {
Serial.begin(115200);
Wire.begin();
}
void loop() {
auto d = ::read_distance();
if (d >= 0) {
Serial.printf("distance: %f mm\r\n", d);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment