Created
June 21, 2022 11:36
-
-
Save hollyhockberry/d2d4cd8cc00b6e547972e6bf9d490a7a to your computer and use it in GitHub Desktop.
M5Stack: UNIT ULTRASONIC-I2C
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 <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