HC-SR04 doesn't work with I2C

Hi everybody,

I have unusual issue with ultrasonic. When my sketch includes I2C library related to RTC - ultrasonic doesn't work. like this below:

#include <Wire.h>
#include <RTClib.h>
#include <NewPing.h>
RTC_DS1307 RTC;

#define TRIGGER_PIN  3 
#define ECHO_PIN  4 
#define MAX_DISTANCE 100 

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); 

void setup()   {
Serial.begin(9600);
Wire.begin();
RTC.begin(); 
 }

void loop() 
{
delay(1000); 
DateTime now = RTC.now(); 
Serial.print("Distance,cm : ");
Serial.println(sonar.ping_cm());
}

I also tried to use ultrasonic code without #include <NewPing.h> with simple code of ultrasonic - Result was the same

digitalWrite(Trig, HIGH); 
  delayMicroseconds(10); 
  digitalWrite(Trig, LOW); 
  impulseTime=pulseIn(Echo, HIGH); 
  distance_sm=impulseTime/58;

But when I remove I2C part of code:

#include <Wire.h>
#include <RTClib.h> 
RTC_DS1307 RTC;

void setup()   {
Wire.begin();
RTC.begin(); 
 }

My ultrasonic works well.

Thanks in advance,
Aleh

I also tried to use ultrasonic code without #include <NewPing.h> with simple code of ultrasonic - Result was the same

I can not confirm your findings, and the following code reads the RTC time and finds the distance to an object with an HC_SR04. Please describe your connections for the ultrasonic unit and the RTC. Can you get time readings from the RTC when it is used alone?
.

#include <Wire.h>
#include <RTClib.h>
//#include <NewPing.h>
RTC_DS1307 RTC;

#define TRIGGER_PIN  3
#define ECHO_PIN   4
#define MAX_DISTANCE 100

//NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup()
{
  Serial.begin(9600);
  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  Wire.begin();
  RTC.begin();
}

void loop()
{
  delay(1000);
  DateTime now = RTC.now();
  Serial.println();
  Serial.print(now.year());
  Serial.print('/');
  Serial.print(now.month());
  Serial.print('/');
  Serial.print(now.day());
  Serial.print(' ');
  if (now.hour() < 10)
    Serial.print("0");
  Serial.print(now.hour());
  Serial.print(':');
  Serial.print(now.minute());
  if (now.minute() < 10)
    Serial.print("0");
  Serial.print(':');
  if (now.second() < 10)
    Serial.print("0");
  Serial.print(now.second());
  Serial.println();

  Serial.print("Distance,cm : ");
  long duration, distance;
  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);
  duration = pulseIn(ECHO_PIN, HIGH);
  distance = (duration / 2) / 29.1;
  //Serial.println(sonar.ping_cm());
  Serial.println(distance);

}

Unfortunately your code doesn't work for me.
RTC always works with/without HC-SR04
my shema is attached. I use Leonardo and RTC (ZS-042)

Thanks,

RTC ZS-042.jpg

On the Leonardo, SDA and SCL are digital pins D2 & D3, so you will have to move your trigger pin.

You are not the first person to be bitten by this.

oh
thank you very much!