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".