Problem reading I2C

Hi everyone,

I'm trying to read the i2c bus(SRF08-sensor) of the arduino UNO, while i'm using the pwm to control 2 dc motor(RfRobot motorshield) . But it seems that using these together. interferes with reading the i2c bus. is there something i can do about this?

this is how my code looks like

void Forwards()
{
	static int sensorReading = 0;
	
	do
	{
	  	// set units, gain, and range location for reading out distance
		MySonar.setUnit(CommandRegister, New_Address, unit, GainRegister, RangeLocation);
		// pause
		delay(time);
		// set register for reading
		MySonar.setRegister(New_Address, ResultRegister);
		// read data from result register
		sensorReading = MySonar.readData(New_Address, 2);
		// print out distance
		Serial.print("Distance: ");
		Serial.print(sensorReading);
		Serial.print(" units");
		Serial.println();

		/*
		analogWrite(E1, 255);	//PWM Speed Control
		analogWrite(E2, 255);	//PWM Speed Control
		delay(30);
		digitalWrite(M1, HIGH);
		digitalWrite(M2, HIGH);
		*/

		if(sensorReading < 10)
		{
			//Serial.print("Distance: is smaller than 10:  ");
			//Serial.print(sensorReading);
			//Serial.println();
			Stop();
			break;
		}
  }while(true);
}
	do
	{
  }while(true);

A complete misuse of the do/while statement. A while statement would be better.

		/*
		analogWrite(E1, 255);	//PWM Speed Control
		analogWrite(E2, 255);	//PWM Speed Control
		delay(30);
		digitalWrite(M1, HIGH);
		digitalWrite(M2, HIGH);
		*/

Is this part of your problem? No? Why did you post it, then?

Where is the rest of your code? What is a MySonar?

But it seems that using these together. interferes with reading the i2c bus.

Some proof would be useful. What does "seems to interfere" mean? What pins is the motor shield using? PWM output on digital pins should have no impact on any analog pins, where I2C occurs.

the problem is de code below yes. E1 = pin 5 of pwm, E2 = pin 6 pwm en digital pin 7 en 4 are M1 and M2

		analogWrite(E1, 255);	//PWM Speed Control
		analogWrite(E2, 255);	//PWM Speed Control
		delay(30);
		digitalWrite(M1, HIGH);
		digitalWrite(M2, HIGH);

the SRF08 is connected to analog pin A5(SCL) en A4(SDA) of the arduino uno. It seems to be interfering because when i read the sensor without using above pwm code it works fine :~

MySonar is the class to read the srf08.

when i read the sensor without using above pwm code it works fine

So, the obvious question is why you are using PWM when you want a 100% duty cycle. digitalWrite(E1, HIGH) achieves the same result without the timer.

thanx PaulS. my toughlesscoding :sweat_smile:

I sloved the problem added some extra AAA battery's and ik works fine now :slight_smile: