1

I have the following code which uses interrupts to set a flag for whether serial IO should happen to update my PC about a particular pin input. So I have interrupts on pins 2 and 3.

I am using the arduino's pin 13 as an output, and every 2 seconds send a pulse. On my arduino, I have 1 wire running from 13 to pin 3. Note: I have nothing at all inserted into pin 2.

Somehow, I get the following input every 2 seconds:

Pin 2 Pin 3

How is my interrupt for pin 2 firing??

boolean serialCommsQueue1 = false;
boolean serialCommsQueue2 = false;

void setup()
{
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), pin2Fired, RISING);
  attachInterrupt(digitalPinToInterrupt(3), pin3Fired, RISING);
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(13, HIGH); // sets the digital pin 13 on
  delay(1000);            // waits for a second
  digitalWrite(13, LOW);  // sets the digital pin 13 off
  delay(1000);            // waits for a second

  if (serialCommsQueue1)
  {
    serialCommsQueue1 = false;
    Serial.println("Pin 2");
  }

  if (serialCommsQueue2)
  {
    serialCommsQueue2 = false;
    Serial.println("Pin 3");
  }
}

void pin2Fired()
{
  serialCommsQueue1 = true;
}

void pin3Fired()
{
  serialCommsQueue2 = true;
}

EDIT:

If I take the wire out of 3, pin 2 constantly (every 2 seconds) writes to serial. If I put the wire back in pin 3 regularly writes every 2 seconds - which itself is a problem too, since it should only be detecting a 'change'?

1
  • 2
    You probably have floating inputs.
    – Majenko
    May 3 '20 at 17:18
2

The interrupt on pin 2 triggers, because the pin is floating. Since nothing is connected to the pin, it reacts to whatever noise is flying by (for example from pin 3). That can lead to the pin changing its state together with pin 3, or to just erratically randomly changing state.

You need to connect a pullup or pulldown resistor (one rather big resistor going from the pin to either Vcc or ground), which sets the pins state, when it is not actively driven otherwise. If you need a pullup or pulldown depends on your wanted behavior.

If a pullup is ok for you, you can activate the Arduinos internal pullup resistor by using

pinMode(2, INPUT_PULLUP);
2
  • I don't think you realise how much hassle this has saved me! Thank you very much mate, I will award a bounty as soon as poss. May 3 '20 at 17:24
  • This is a common issue with CMOS digital inputs. If they are not connected through a resistor (10k is a good choice) to either +5V or ground, they give semi-random 1s and zeros.
    – Duncan C
    May 3 '20 at 20:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.