Why is this sensor turning on and off randomly?

Hi,

Below is the following code I've made for a button and two sensors to run at the same time;

void loop() {
  //collect();
  //delay(2000);
  int x, y, z; //triple axis data

  //Tell the HMC what regist to begin writing data into
  Wire.beginTransmission(address);
  Wire.write(0x03); //start with register 3.
  Wire.endTransmission();


  //Read the data.. 2 bytes for each axis.. 6 total bytes
  Wire.requestFrom(address, 6);
  if (6 <= Wire.available()) {
    x = Wire.read() << 8; //MSB  x
    x |= Wire.read(); //LSB  x
    z = Wire.read() << 8; //MSB  z
    z |= Wire.read(); //LSB z
    y = Wire.read() << 8; //MSB y
    y |= Wire.read(); //LSB y
  }

  //Wipes the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  //Puts the trigger on HIGH for 10 us
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  //read from the echoPin
  duration = pulseIn(echoPin, HIGH); // waits for pin to go high, then records time it takes to go LOW

  //calculate the distance
  distance = duration * (0.034 / 2);

  // print the distance

  Serial.print("Distance: ");
  Serial.println(distance);

  buttonState = digitalRead(buttonPin);// current state of button

  if (buttonState != lastState) { // if the state differs
    if (buttonState == LOW) { // if the button is pushed
      if (currentMode == 0) { // and we are not already in "on" mode
        digitalWrite(13, HIGH);
        Serial.println("on");
        currentMode = 1; // turn us into "on" mode
      }
      else if (currentMode == 1) {
        digitalWrite(13, LOW);
        currentMode = 0; // take us out
        Serial.println("off");
      }
    }
    else { // button is not pressed but was in last loop
      Serial.println("off");
    }
    delay(50); // debounce thing
  }
  lastState = buttonState; // update last state
  Serial.println("Current mode is: ");
  Serial.print(currentMode);
  Serial.print(z);

The set up of this is simply turning wire on (I don't see that as affecting this). Individually, these sensors work fine; I have three seperate programs for each element and alone they are as perfect as they could be. However, when together, the Ultrasonic sensor seems to be turning off every couple of seconds; the printed distance is accurate for a second before dropping to 0 and reclimbing back to accuracy.

This is an issue as I want to have this sensor be arguably the most accurate so I don't have my robot crash into a wall and blow up. Is there any reason why this is happening, and anything I can do to fix it?

That's not you whole program :wink: It misses all declarations. And telling us what's connected exactly is mandatory :wink: And things like, how is it connected? What is powering it? etc.

And a couple of tips:

Short (en especially single letter variable names are not very handy nor clear.

Don't try to write everything as one big block. Break it up in pieces called functions. You should kind of be able to explain a function by it's name or in one sentance. It's then more clear to have

loop(){
  readSomeSensor();
  readDistanceSensor();
  readButton();
  updateMotors();
  //etc
}

Edit: It did identify the issue actually, it appears a servo I have is causing it to turn off and on; is this maybe due to it using too much power? I've definitely found the functions much more readable, I deleted the servo code for online copying and that appears to have fixed it so I'm not sure how I would go about getting servo to work with this sensor now.

Edit #2: I'm going to just detach the servo when its not in use and hopefully that will rectify the issue. Still big thank you for making it very quick to identify this issue!

is this maybe due to it using too much power?

Not if the servo is powered correctly. If you are trying to make the Arduino provide the power, yes that is a problem.

PaulS:
Not if the servo is powered correctly. If you are trying to make the Arduino provide the power, yes that is a problem.

This is most likely it, I'm only using the USB power supply from my computer right now, once this is hooked up to the relevant battery packs it should have the necessary power to handle all the components when needed. Thanks guys!

Power the servo separately from the Arduino, or you will have trouble.

The USB port on a computer is indeed not enough for a servo. A small servo can draw 1A+ with ease.

And what kind of battery is it? The (onboard regulator on the) Arduino can NOT provide current to a servo. If it's a 4V-5V pack and you connect it to Vcc/5V (instead of Vin/RAW) you can also connect it to the servo. But even then I would isolate the Arduino power from the servo power.