Sensor Interfering High Input Lag With Debounce

Noob Arduino programmer here. I'm using the Bounce2 library to debounce six input signals and using an HC-SR04 as a distance gauge. When I run the sensor it seriously lags the Arduino from registering inputs. Running the sensor itself is clearly the problem as if I comment out that subroutine the lag disappears. Neither the sensor nor the six input debounce have any issues separately so I'm guessing there's a conflict between the two.

Any help here would be really appreciated.

#include <Bounce2.h>

//SETTINGS
const byte StopDistance = 20;              //Car stop distance (in cm)
const long SCinterval = 1000;              //Time between stop checks
const int MotorSpeedIncr = 50;             //Value to increase/decrease speed by

//Calibrate then move to constants (current values are arbitrary)
const int MotorSpeedMax = 250;             //Maximum motor speed (above which values don't affect speed, use tach to find)
const int MotorSpeedMin = 70;              //Minimum motor speed (where shaft doesn't turn, effectively zero)

//PINS
const int trigPin = 2;                     //SENSOR - Trig
const int echoPin = 8;                     //SENSOR - Echo
const int BrakeLED = 12;                   //LED - Brake Lights
const int HeadLED = 13;                    //LED - Headlights
const int BT1 = A0;                    //REMOTE - Button 1
const int BT2 = A1;                    //REMOTE - Button 2
const int BT3 = A2;                    //REMOTE - Button 3
const int BT4 = A3;                    //REMOTE - Button 4
const int BT5 = A4;                    //REMOTE - Button 5
const int BT6 = A5;                    //REMOTE - Button 6
const int ledPin =  13;      // the number of the LED pin

const int enA = 9;                         //MOTOR - Enable A
const int in1 = 4;                         //MOTOR - Input 1
const int in2 = 5;                         //MOTOR - Input 2
const int enB = 10;                        //MOTOR - Enable B
const int in3 = 6;                         //MOTOR - Input 3
const int in4 = 7;                         //MOTOR - Input 4

//START CONDITIONS


//CONSTANTS


//VARS
long dura;                            //SENSOR - duration of received pulse
int dist;                             //SENSOR - distance from sensor in cm
int MotorSpeed;                           //MOTOR - current motor speed

bool stopped;                             //High if vehicle is stopped
bool ASOverride;                          //If high, engages override, disables autostop system

bool ForRev = 1;                              //Forward/reverse toggle → 1 = for, 0 = rev

bool ButtonSt1 = 0;                      //REMOTE - Button 1 state
bool ButtonSt2 = 0;                      //REMOTE - Button 2 state
bool ButtonSt3 = 0;                      //REMOTE - Button 3 state
bool ButtonSt4 = 0;                      //REMOTE - Button 4 state
bool ButtonSt5 = 0;                      //REMOTE - Button 5 state
bool ButtonSt6 = 0;                      //REMOTE - Button 6 state

//Timer & Cycle Storage
unsigned long SCprevMillis = 0;          //will store last time stopcheck occured

//DEBOUNCERS
Bounce debouncer1 = Bounce();
Bounce debouncer2 = Bounce();
Bounce debouncer3 = Bounce();
Bounce debouncer4 = Bounce();
Bounce debouncer5 = Bounce();
Bounce debouncer6 = Bounce();



void setup()
{

  //PIN MODES
  pinMode(trigPin, OUTPUT);                 //SENSOR
  pinMode(echoPin, INPUT);                  //SENSOR
  pinMode(BrakeLED, OUTPUT);                //LED - Brake Lights
  pinMode(HeadLED, OUTPUT);                 //LED - Headlights

  pinMode(BT1, INPUT);                  //REMOTE - Button 1
  pinMode(BT2, INPUT);                  //REMOTE - Button 2
  pinMode(BT3, INPUT);                  //REMOTE - Button 3
  pinMode(BT4, INPUT);                  //REMOTE - Button 4
  pinMode(BT5, INPUT);                  //REMOTE - Button 5
  pinMode(BT6, INPUT);                  //REMOTE - Button 6
  pinMode(ledPin, OUTPUT);

  //DEBOUNCE
  pinMode(BT1, INPUT_PULLUP);
  pinMode(BT2, INPUT_PULLUP);
  pinMode(BT3, INPUT_PULLUP);
  pinMode(BT4, INPUT_PULLUP);
  pinMode(BT5, INPUT_PULLUP);
  pinMode(BT6, INPUT_PULLUP);
  debouncer1.attach(BT1);
  debouncer1.interval(25);
  debouncer2.attach(BT2);
  debouncer2.interval(25);
  debouncer3.attach(BT3);
  debouncer3.interval(25);
  debouncer4.attach(BT4);
  debouncer4.interval(25);
  debouncer5.attach(BT5);
  debouncer5.interval(25);
  debouncer6.attach(BT6);
  debouncer6.interval(25);

  //SERIAL
  Serial.begin(9600);                   // Starts the serial communication
}

void loop()
{
  DBup();
  BTmap();
  RunDistanceSensor();
  CheckForStopDist();
  CheckIfStopped();
}

void RunDistanceSensor()
{
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  dura = pulseIn(echoPin, HIGH);
  // Calculating the distance
  dist = dura * 0.034 / 2;
}

void CheckForStopDist()
{
  if (dist <= StopDistance)             //if distance is equal or less than set distance
  {

  }
}

void CheckIfStopped()
{
  unsigned long SCcurrentMilis = millis();            //var for StopCheck
  static int ReadToggle = 0;                          //toggle capture of distance #1 or #2 (static keeps value but keeps var local)
  static int prevdist1;                               //distance captured alternating interval
  static int prevdist2;                               //distance captured alternating interval

  if (SCcurrentMilis - SCprevMillis >= SCinterval)    //perform container actions every SCinterval
  {
    SCprevMillis = SCcurrentMilis;                    //save last time reading was taken
    ReadToggle = !ReadToggle;                         //toggle read distance #1 or #2

    if (ReadToggle == 1)
    {
      prevdist1 = dist;                           //take distance reading #1
    }
    else if (ReadToggle == 0)
    {
      prevdist2 = dist;                           //take distance reading #2
    }
  }

  if (dist < 3000 && prevdist1 - prevdist2 == 0)  //under 3000 if dist 1 = dist 2 car is stopped
  {
    stopped = 1;
  }
}

void DBup()
{
  debouncer1.update(); // Update the Bounce instance
  debouncer2.update(); // Update the Bounce instance
  debouncer3.update(); // Update the Bounce instance
  debouncer4.update(); // Update the Bounce instance
  debouncer5.update(); // Update the Bounce instance
  debouncer6.update(); // Update the Bounce instance
}

void BTmap()
{
  But1();
  But2();
  But3();
  But4();
  But5();
  But6();
}

void But1()
{
  if (debouncer1.rose() )
  {
    Serial.println("Button 1 Press");
  }
}

void But2()
{
  if (debouncer2.rose() )
  {
    Serial.println("Button 2 Press");
  }
}

void But3()
{
  if (debouncer3.rose() )
  {
    Serial.println("Button 3 Press");
  }
}

void But4()
{
  if (debouncer4.rose() )
  {
    Serial.println("Button 4 Press");
  }
}

void But5()
{
  if (debouncer5.rose() )
  {
    Serial.println("Button 5 Press");
  }
}

void But6()
{
  if (debouncer6.rose() )
  {
    Serial.println("Button 6 Press");
  }
}

You might want to re-visit your use of pulseIn(). There's an optional 3rd parameter that represents a time-out value to be used in case the pulse timing exceeds a threshold. Without that you could be in for some non-deterministic delays.

Hi,
Look up NewPing library, it does all the SR-04 work for you.

Tom... :slight_smile:

Thanks to both of you for replying. Somehow manually specifying even the default time-out fixes the problem.