Advertisement
microrobotics

GY-US42 Ultrasonic Rangefinder Serial/I2C

Mar 31st, 2023
1,267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. 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:
  3.  
  4. 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.
  5.  
  6. This code will continuously read the distance from the GY-US42 sensor and print it on the Serial Monitor in centimeters.
  7. */
  8.  
  9. #include <Wire.h>
  10.  
  11. const int GY_US42_ADDR = 0x70; // GY-US42 I2C address
  12.  
  13. void setup() {
  14.   Serial.begin(9600);
  15.   Wire.begin();
  16.  
  17.   // Configure GY-US42 for distance measurement
  18.   Wire.beginTransmission(GY_US42_ADDR);
  19.   Wire.write(0x26); // Register address
  20.   Wire.write(0x01); // Command for distance measurement in centimeters
  21.   Wire.endTransmission();
  22. }
  23.  
  24. void loop() {
  25.   int distance = readGY_US42Distance();
  26.  
  27.   if (distance >= 0) {
  28.     Serial.print("Distance: ");
  29.     Serial.print(distance);
  30.     Serial.println(" cm");
  31.   } else {
  32.     Serial.println("Failed to read data from GY-US42");
  33.   }
  34.  
  35.   delay(500); // Wait 500ms between readings
  36. }
  37.  
  38. int readGY_US42Distance() {
  39.   // Request distance measurement data
  40.   Wire.beginTransmission(GY_US42_ADDR);
  41.   Wire.write(0x66); // Register address
  42.   Wire.endTransmission(false);
  43.  
  44.   // Read distance measurement data (2 bytes)
  45.   Wire.requestFrom(GY_US42_ADDR, 2);
  46.   if (Wire.available() == 2) {
  47.     byte highByte = Wire.read();
  48.     byte lowByte = Wire.read();
  49.     int distance = (highByte << 8) | lowByte;
  50.     return distance;
  51.   } else {
  52.     return -1; // Failed to read data
  53.   }
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement