Restart loop when digitalPin is open again.

Hi,

I'm trying to do some servo commands while recording data from BNO055 to MicroSD card. However, one step by another, I'm having problems with the restart of the loop of the servo.

  1. While digitalPin 8 is connected to ground (closed), I upload the program to Arduino Uno
  2. When the digitalPin 8 connection is open, the servo should do it's job and stop after 3 times.
  3. When I close the digitalPin 8 connection again with ground and open it again, the loop with the counter should start again 3 times.

I hope you understand what I mean. I tried different ways like for, if or while functions, but it never worked as I imagined. Can you please help me with this?
At the moment I'm trying to do it with the if function, but it only worked with "LOW" state and only one time. I can't figure it out.

#include <Servo.h>   

Servo servo1;           // create servo object to control a servo
int angle;              // position in degree
int counter = 0;


void setup()
{
  Serial.begin(9600);
  pinMode(8,INPUT_PULLUP);   //pin 8 forces to HIGH when there is no external input
  servo1.attach(2);          //attaches servo1 to digital pin 2
  servo1.write(0);           //tells servo1 to go to 0 degree position
}


void loop()
{
if (digitalRead(8) == HIGH)
{  
  if(counter<3)
  {
    for (angle = 0; angle < 80; angle += 5)
    {
    servo1.write(angle);
    delay(15);
    }
  counter = counter+1;
  }
}
}

The difference between HIGH and LOW state depends on how you wire whatever switch you have connected to the pin.

It only runs once, because your counter increments at the end of the loop each time around. As long as your pin reads HIGH, counter keeps going up. Once it reaches 3, the test if(counter<3) fails and the servo code does not get executed.

So HIGH is the right choice for my "if" function, but I need to write a command which resets the counter if the "digitalRead" is LOW again, correct? That's the point I have problems with.

Jogibaer:
but I need to write a command which resets the counter if the "digitalRead" is LOW again, correct? That's the point I have problems with.

You just need an else. If the pin isn't HIGH then it must be low again. So give yourself an else part to set it back to 0.

if(the pin is HIGH){

   counter += 1;
}
else {
   counter = 0;
}

Haha, oh no, I already had the "else" command one time in it, but it was written too complicated. :sweat_smile:

Thank you very much, it works. :smiley: