Need help with coding an Arduino uno/Adafruit motor shield v1 and PIR sensor

I'm trying to get one stepper motor to run when PIR sensor senses motion using an Arduino Uno and Adafruit motor shield v1. I have tested the Adafruit motor shield/Arduino and can run the stepper motor without the PIR. And, I have tested the PIR with an LED and it works fine but I obviously have the code wrong for the combination. Any help would be appreciated. The board does nothing with my current code.

#include <AFMotor.h>

int pirPin = 8;

int motionStatus = 0;
int pirState = 0;

AF_Stepper Stepper1(200, 2);



void setup() {
  Serial.begin(9600);
  pinMode(pirPin, INPUT);
  delay(2000);

  Stepper1.step(200, FORWARD, INTERLEAVE);
  Stepper1.setSpeed(10);
}

void loop() {
  motionStatus = digitalRead(pirPin);

  if (motionStatus == HIGH) {

    if (pirState == LOW) {
      Serial.println("Motion Detected");
      pirState = HIGH;

      Stepper1.step(2000, FORWARD, INTERLEAVE);  // turn it on going forward
      delay(1000);

    } else {

      if (pirState == HIGH)
        ;
      Serial.println("Motion Ended");
      pirState = LOW;
    }
  }
}

When triggered, the PIR stays high for maybe five seconds, not letting the program flow outside this condition until the PIR goes low...

  if (motionStatus == HIGH) {

Maybe "set a flag" rather than hold the program in the if() conditional loop, then test the flag, and if the flag is set, rotate the motor.

That's an interesting idea. I understand what you are saying but I don't know how to implement "a flag" in the code. What does that look like? Thanks for taking the time to look at my problem!

if (motionStatus == HIGH)
  flag = 1;

Your code treats motion as "it is happening" and pir as "it happened." See if you can move your motor on motion detected and not on pirstate.

That didn't fix it. I'm wondering if it needs to somehow say the stepper motor is the output. I can't find any examples of that with this motor shield. It just says something like this Stepper1.setSpeed(10); Stepper1.step(200, FORWARD, INTERLEAVE); Does that alone make it an output?

What didn't fix it?

This else is a condition of the second if() condition, but it should be a condition of the first if() condition. To see what I mean, format your code. The open brace of the } else { should line up with the first if() (not the second if()).

Your code (mis-aligned else):

  if (motionStatus == HIGH) {
    if (pirState == LOW) {
      Serial.println("Motion Detected");
      pirState = HIGH;
      Stepper1.step(2000, FORWARD, INTERLEAVE);
      delay(1000);
    // } // missing this close brace
    } else {

Properly aligned...

  if (digitalRead(inputPin) == HIGH) {
    if (pirState == LOW) {
      Serial.println("Motion detected!");
      pirState = HIGH;
    }
  } else {

YES! That is it. It is working properly. Thank you!

1 Like

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