Electronics > Beginners

Arduino PIR

(1/3) > >>

darinsquared:
I use the following code for a PIR sensor triggering a LED:
int led = 13;               
int sensor = 2;             
int state = LOW;         
int val = 0;               

void setup() {
  pinMode(led, OUTPUT);      // initalize LED as an output
  pinMode(sensor, INPUT);    // initialize sensor as an input
  Serial.begin(9600);        // initialize serial
}

void loop(){
  val = digitalRead(sensor);   // read sensor value
  if (val == HIGH) {           // check if the sensor is HIGH
    digitalWrite(led, HIGH);   // turn LED ON
    delay(100);                // delay 100 milliseconds
   
    if (state == LOW) {
      Serial.println("Motion detected!");
      state = HIGH;       // update variable state to HIGH
    }
  }
  else {
      digitalWrite(led, LOW); // turn LED OFF
      delay(200);             // delay 200 milliseconds
     
      if (state == HIGH){
        Serial.println("Motion stopped!");
        state = LOW;       // update variable state to LOW
    }
  }
}

Everything works fine when I have Arduino connected through USB to my computer.  When I disconnect from USB and operate from the 9V battery only the LED blinks constantly.  What is my error?

igendel:
What is the power source of the sensor?

darinsquared:

--- Quote from: igendel on December 07, 2019, 08:31:27 pm ---What is the power source of the sensor?

--- End quote ---

PIR connected directly to 5V and ground on Arduino and Arduino board connected to 9V battery

darinsquared:
more info: when I disconnect the USB so only (9V battery is connected) the LED is off until PIR is triggered. At that point the LED is ON the length of time as set on its POT then is off approximately 2 seconds then ON again repeatedly.

igendel:

--- Quote from: darinsquared on December 07, 2019, 09:23:41 pm ---more info: when I disconnect the USB so only (9V battery is connected) the LED is off until PIR is triggered. At that point the LED is ON the length of time as set on its POT then is off approximately 2 seconds then ON again repeatedly.

--- End quote ---

I assume it's one of those HC-SR501 modules? They have a 2-seconds "dead time" window between the end of a one signal and the beginning of the next. Now, assuming the wiring is correct and that the battery is fresh, there should be no difference in behavior. It would seem the PIR sensor still picks something up, this can happen especially near power-up when it's trying to stabilize. Perhaps it was in a different place/angle when it was connected with USB? try putting something over it so that it's blind, check what happens then with USB and with battery.

Navigation

[0] Message Index

[#] Next page

There was an error while thanking
Thanking...
Go to full version
Powered by SMFPacks Advanced Attachments Uploader Mod