Value changes and Arduino

I hope you can help me - I¨m sure it's not too complicated, I just know yet how to ask my Arduino to read it. 

 

So, I'm playing peek-a-boo with my robot (arduino, light sensor and a motor)

and I need to tell my arduino to read that:

If the value of the LDR (which is usually around 600) goes below 100 (for more than 2 sec) and then above 400, it should trigger the motor. 

 

Thanks a bunch, 

Trommp, and Moon (the robot)

Paste this into an empty Arduino IDE and try it

/* simple untested LDR trigger for Moon (the Robot). Smoothing may be required.

See the “analog > smoothing” example on the official arduino website   */

boolean firstTrigger=false; //tells the duino if the LDR level is below 100

const int sensor=0; //or whatever your LDR sensor is. 

const int MotorPin1 = 4; //or whatever

const int MotorPin2 = 5; //or whatever

 

void setup(){

  //initialise your motor pins

  pinMode(MotorPin1,OUTPUT);

  pinMode(MotorPin2,OUTPUT);

}

 

void loop(){

  //trigger timer loop by initial activation.

 if (analogRead(sensor) < 100){

   //2 second timer loop. LDR of greater than 100 will break the loop, thus going back to start

   for (int i=0; i < 200; i++){

    if (analogRead(sensor) > 100) break;

    if (i == 200) firstTrigger=true;

    delay(10);//10 x 200 = 2000 ms = 2 seconds

  }

 }

    //we’ve made it at least 2 seconds on low

    if (firstTrigger){

      if (analogRead(sensor) > 400) Motor();

    }

}//end of primary loop

    void Motor(){

//assumes an H-bridge of some sort

     digitalWrite(MotorPin1,HIGH); 

     digitalWrite(MotorPin2,LOW);      

    }

oops

probably want to change the “200” in the for loop to “201”:

for (int i=0; i < 201; i++){

you might want to do a while
you might want to do a while loop instead and keep checking after the 2 seconds is up otherwise the user would have to move their hand at exactly 2 seconds which would be unlikely

it’s a flag

Not so. Once the 2 continuous seconds is over, then the trigger boolean is true. The timing doesn’t matter after that point.

You are so helpful! :smiley:

Thanks a bunch! 

It’s not working yet - but hopefully soon. 

Why do we have motorPin1 and motorPin2 ?

 

for the motor

The code just assumes that you’re using an H-Bridge for your motor, in which case you would need 2 pins. If you only need one direction for your motor, one pin is all you need. Google “H-bridge” if you have any questions about what that is.

:smiley:

It works!!!

:smiley:

Brilliant! 

Now we can play peek a boo all day :wink:

We had to change it a little - but used the base. 

Ahhh true… I guess because

Ahhh true… I guess because it’s a different way than I’d do it for some I couldn’t get into my head how the code flowed properly :slight_smile: