Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- The GY-US42 is an ultrasonic rangefinder that can communicate using both UART and I2C protocols. Here's an example of how to use the GY-US42 sensor with an Arduino via I2C to read the distance and display it on the Serial Monitor:
- To wire the GY-US42 sensor, connect its VCC pin to the 5V or 3.3V pin on the Arduino (depending on your sensor's voltage range), the GND pin to the ground, the SDA pin to the SDA (A4) pin on the Arduino, and the SCL pin to the SCL (A5) pin on the Arduino. Make sure to connect the ADDR pin to GND to set the I2C address to 0x70.
- This code will continuously read the distance from the GY-US42 sensor and print it on the Serial Monitor in centimeters.
- */
- #include <Wire.h>
- const int GY_US42_ADDR = 0x70; // GY-US42 I2C address
- void setup() {
- Serial.begin(9600);
- Wire.begin();
- // Configure GY-US42 for distance measurement
- Wire.beginTransmission(GY_US42_ADDR);
- Wire.write(0x26); // Register address
- Wire.write(0x01); // Command for distance measurement in centimeters
- Wire.endTransmission();
- }
- void loop() {
- int distance = readGY_US42Distance();
- if (distance >= 0) {
- Serial.print("Distance: ");
- Serial.print(distance);
- Serial.println(" cm");
- } else {
- Serial.println("Failed to read data from GY-US42");
- }
- delay(500); // Wait 500ms between readings
- }
- int readGY_US42Distance() {
- // Request distance measurement data
- Wire.beginTransmission(GY_US42_ADDR);
- Wire.write(0x66); // Register address
- Wire.endTransmission(false);
- // Read distance measurement data (2 bytes)
- Wire.requestFrom(GY_US42_ADDR, 2);
- if (Wire.available() == 2) {
- byte highByte = Wire.read();
- byte lowByte = Wire.read();
- int distance = (highByte << 8) | lowByte;
- return distance;
- } else {
- return -1; // Failed to read data
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement