0

I'm writing this piece of code for Arduino Uno, which takes in input on pin 2 the value of a PIR sensor. In order to debug, in this moment I'm taking the signal on pin 2 from the 5V power supply:

int inputPinSensor1 = 2; // input pin for sensor 1
int sensor_1_State = LOW; // we start assuming no motion detected for sensor 1
int val = 0; // variable for reading the pin status

void setup() {
  pinMode(inputPinSensor1, INPUT); // declare sensor 1 pin as input

  Serial.begin(9600);
}

void loop(){
  detectChange(&inputPinSensor1, &sensor_1_State);
}

void detectChange(int* inputPin, int* pirState) {
  // read input value
  val = digitalRead(*inputPin);
  // check if the input is HIGH
  if (val == HIGH) {
    if (*pirState == LOW) {
      // we have just turned on
      Serial.println("Current detected");
      *pirState = HIGH;
    }
  } else {
    if (*pirState == HIGH){
      // we have just turned off
      Serial.println("Current ended");
      *pirState = LOW;
    }
  }
}

This code should detect the passage from a LOW value to an HIGH value on pin 2, and vice versa. In this way I'm expecting to have an HIGH value on pin 2 when I connect the jumper and a LOW value when I disconnect the jumper. But what I get is two possible behaviors: sometimes I get "Current detected" at the begin of the execution, after which there are no further messages, and sometimes I get a rapid alternation of "Current detected" and "Current ended".

  • You disconnect a wire? Disconnected does not equal LOW. Disconnected equals "Unknown". LOW is connected to GND. What you have there is a "floating input". – Majenko Dec 9 '19 at 11:30
  • As a side note, the input pins detect voltage, not current. – Edgar Bonet Dec 9 '19 at 12:00
  • @Majenko [at]EdgarBonet Thank you for your answers. Yes, I was able to get the LOW value read when I connected the jumper to ground. Thank you! – mark247m Dec 10 '19 at 11:00
1

As Majenko says in their comments, a pin that's not connected to anything "floats" and gives unpredictable results.

You either need to connect such a pin to ground through a "pull-down" resistor or to +5V through a "pull-up" resistor. (10KΩ is a good value to start with.)

If you connect the pin to +5V through a pull-up resistor then you would ground it to change it's state. In that case the pin reads HIGH normally, and drops to LOW when triggered. Note that the Arduino has a special mode, INPUT_PULLUP, that connects the pin to an internal pull-up resistor. In that case you don't need an external pull-up resistor.

In your case, connect the pin to ground with a 10KΩ restistor. Then when you want the pin to go high attach the pin to +5V. That will swamp the connection to ground and pull the pin up to just below 5V.

| improve this answer | |

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.