Ultrasonic Sensor scanning too often resulting in a whirring noise I am using an HC-SRO4 ultrasonic sensor for a wall-avoidance, maze-solving robot. However, I have recently run into an issue where I am getting a whirring noise from the sensor because it is taking measurements way too often.

This is the code I have right now:

const int serialPeriod = 250;       // only print to the serial console every 1/4 second
unsigned long timeSerialDelay = 0;

const int loopPeriod = 20;          // a period of 20ms = a frequency of 50Hz
unsigned long timeLoopDelay   = 0;

// specify the trig &amp; echo pins used for the ultrasonic sensors
const int ultrasonic2TrigPin = 8;
const int ultrasonic2EchoPin = 9;

int ultrasonic2Distance;
int ultrasonic2Duration;

void setup()
{
    Serial.begin(9600);

    // ultrasonic sensor pin configurations
    pinMode(ultrasonic2TrigPin, OUTPUT);
    pinMode(ultrasonic2EchoPin, INPUT);
}


void loop()
{
    debugOutput(); // prints debugging messages to the serial console

    if(millis() - timeLoopDelay &gt;= loopPeriod)
    {
        readUltrasonicSensors(); // read and store the measured distances

        timeLoopDelay = millis();
    }
}


void readUltrasonicSensors()
{
    // ultrasonic 2
    digitalWrite(ultrasonic2TrigPin, HIGH);
    delayMicroseconds(10);                  // must keep the trig pin high for at least 10us
    digitalWrite(ultrasonic2TrigPin, LOW);

    ultrasonic2Duration = pulseIn(ultrasonic2EchoPin, HIGH);
    ultrasonic2Distance = (ultrasonic2Duration/2)/29;
}



void debugOutput()
{
    Serial.print("timeSerialDelay: ");
    Serial.print(timeSerialDelay);
    Serial.println();

    if((millis() - timeSerialDelay) &gt; serialPeriod)
    {
        Serial.print("ultrasonic2Distance: ");
        Serial.print(ultrasonic2Distance);
        Serial.print("cm: ");
        Serial.println();

        timeSerialDelay = millis();
    }
}


and my wiring:



Link to product

Does anyone know why the scanning is happening constantly? It should only be happening every 1/4 of a second, not constantly. The weird thing is that this wasn't happening earlier before I started using the cable. 

I believe it has something to do with the 8.5" extension cable I have (needed because I can't mount three sensors, one facing to each side and one in front, on a single breadboard). This is because when I mounted the sensor directly onto the breadboard, the delay was correct and the whirring was not present. However, as I just mentioned, I need the extension cable to be able to have the three sensors.

Does anyone have a solution for this?

Thanks!
If you want to sample at 4Hz (4 times per second), you need to change your headers accordingly:

const int serialPeriod = 250;       // only print to the serial console every 1/4 second
unsigned long timeSerialDelay = 0;

const int loopPeriod = 250;          // a period of 250ms = a frequency of 4Hz
unsigned long timeLoopDelay   = 0;