Home

How to Read from an Active Low Digital Input

An active low digital input reads as false/0/LOW when the attached digital sensor is active (e.g. button pressed, door open, engine overheated, or motion detected). An active low sensor has a logic state that is the opposite of its physical state, meaning you must read its state with !digitalRead(pin) instead of digitalRead(pin).

It is very common to wire switch contacts (e.g. a momentary button switch or a magnetic reed switch) from a digital input to GND and enable the internal pullup resistor. When the switch is open, the pullup resistor pulls the digital input up to +5V/true/1/HIGH. When the switch is closed, it pulls the digital input down to 0V/false/0/LOW/GND.

#define BUTTON1 2  // Momentary button switch connected from D2 to GND

void setup()
{
  pinMode(BUTTON1, INPUT_PULLUP);
}

void loop()
{
  // Local persistent logic state variable, value preserved between calls
  // to loop()
  static bool oldstate;

  // Local nonpersistent logic state variable, value NOT preserved between
  // calls to loop()
  bool newstate;

  // Read digital input state into a logic state variable
  newstate = !digitalRead(BUTTON1);

  // Do something if the sensor input is active
  if (newstate)
  {
    DoSomething();
  }

  // Do something if the sensor input is active (do not save state)
  if (!digitalRead(BUTTON1))
  {
    DoSomething();
  }

  // Do something if the sensor input is active (save state)

  if (newstate = !digitalRead(Sensor1))
  {
    DoSomething();
  }

  // Do something if the sensor input CHANGES

  if (newstate != oldstate)
  {
    DoSomething();
  }

  // Save logic state for next call to loop()
  oldstate = newstate;
}

Home


Questions or comments to phil@munts.net