0

I just got an Arduino and an Infrared motion detection module. What I tried making is, that if the module detected movement, a led would turn on, and if it detected movement again, it would turn off. So I wrote this code and tried looking online for solutions, but couldn't find it. I really don't know what to change about my code to make it work. Does anyone have solutions for this?

(Sensor value can be 0 or 1, 0 means nothing detected, 1 means something detected. After detection the value automatically goes back to 0 in a few seconds)

int Sensor = 4;
int led = 13;
bool bool1 = false;

void setup() {
pinMode(Sensor, INPUT);
pinMode(led, OUTPUT);
Serial.begin(9600);
}

void loop() {
int SensorValue = digitalRead(Sensor);

if(SensorValue == 1){
  bool1 = !bool1;
  }

if(bool1 == true){
  digitalWrite(led, HIGH);
  }
if(bool1 == false){
  digitalWrite(led, LOW);
  }
}
1
  • what to change about my code to make it work .... what is wrong with the way the code behaves right now?
    – jsotola
    Nov 19 '18 at 0:31
1

Consider using a state machine with 4 states. Currently you only have 2 states. One where "bool1" is TRUE and another when "bool1" is FALSE. The 4 states needed are:

  1. When the LED is OFF & the PIR is NOT-ACTIVE.
  2. When the LED is OFF & the PIR is ACTIVE.
  3. When the LED is ON and the PIR is ACTIVE.
  4. When the LED is ON and the PIR is NOT-ACTIVE.

As you travel between these 4 states, you will find you only want to turn the LED ON when traveling between states 2 & 3. And you will only want to turn the LED OFF when traveling between states 4 & 1.

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.