Arduino Motion Sensor Light?

Hi there, my class is trying to create motion sensor-controlled lights using an Arduino Uno and a PIR sensor. I have found projects such as this online, however we are trying to code it modeled off of the projects in the Arduino Project book. So far we have yet to make it work, and I'm not sure what we are doing wrong. Below is a sample of one of the codes my students came up with. The LED is attached to pin 3, the sensor is attached to pin 4. Why would this not work? Thank you!

int switchState = 0;
void setup(){
pinMode(3, OUTPUT);
pinMode(4, INPUT);
}
void loop (){
  switchState = digitalRead(4);
 
if (switchState = HIGH) {
  digitalWrite(4, HIGH); 
  delay(10000);
}
else{
digitalWrite(4, LOW); 
}
}

A few things. Thanks for using the CODE/ tag, but please use Ctrl + t in the software first to align it. It makes it easier to read.

Have you tried the blink example code in the IDE to make sure the LED comes on like it's supposed to?

There is a difference you need to make between these two statements. Check out == - Arduino Reference

I like using defines for the pins, pretty easy to get the numbers confused, like you did..

#define LED_PIN 3
#define PIR_PIN 4

int switchState = 0;
void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(PIR_PIN, INPUT);
}
void loop () {
  switchState = digitalRead(PIR_PIN);

  if (switchState == HIGH) {
    digitalWrite(LED_PIN, HIGH);
    delay(10000);
  }
  else {
    digitalWrite(LED_PIN, LOW);
  }
}

PIRLED

good luck.. ~q

I'm sorry, I posted that in a rush before leaving work and chose the wrong student's code. Here is a better example, where the pinModes are correct for the LED and the PIR, and the == is used.

void setup() {
  pinMode(5, OUTPUT);
  pinMode(3, OUTPUT);
}

void loop() {
    switchState = digitalRead(3);
    if (switchState == HIGH) {
      digitalWrite(5, HIGH);
      delay(60000);
    }
    else {
      digitalWrite(5, LOW);
    }```

No input??

sorry.. ~q

here's a non blocking approach..

#define LED_PIN 3
#define PIR_PIN 4

int switchState = 0;
unsigned long lastTime = 0;
int intervalOn = 1000;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(PIR_PIN, INPUT);
}
void loop () {

  bool  motion = digitalRead(PIR_PIN);

  if (motion && !switchState) {
    switchState = motion;//remember
    digitalWrite(LED_PIN, HIGH);
  } else if (!motion && switchState) {
    if (millis() - lastTime >= intervalOn)
    {
      lastTime = millis();
      switchState = false;
      digitalWrite(LED_PIN, LOW);
    }
  }
}

updated sim link posted earlier too..
have fun.. ~q

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.