Simple servo + button + led Question

PaulS:
digitalRead() returns an int, not a boolean. This debounce code sucks.

I use a boolean, because I read in the doc that digitalRead() returns HIGH or LOW, so the boolean seemed fit.

It's really hard to tell, from these names, whether currentButton refers to a switch number, a pin number, or a switch state. Better variable names would be in order.

See the new code attach if it makes more sense.

How is your switch wired?

One leg to pin8 the other to a pull down resistor which is connected to ground.

After your sketch has been running for 32 seconds, what is going to happen? Look at the millis() documentation again. The function returns an unsigned long for a reason.

Thanks, for that hint went to check in the doc and it always return a unsigned long. Thinking back it may be one of the reason it failed.

does the same thing, and is guaranteed to work. But, count is a lousy name, since you aren't counting anything.

I changed my code to have the to variable subtract from each other. That also caused me some problem too. I also changed my variable name from count to time.

Why are you not using the Servo library? It makes dealing with the servo so much easier.

Because I like to program myself basic stuff in order to understand what is happening first. Once I understand what is going on I will either build my own libraries (for fun) or use the one provided.

With the few pointer you provided me the code is now working perfectly fine

Thank You
M.

nt switchPin = 8;
int ledPin = 13;
int servoPin = 3;

boolean lastButtonState = LOW;
boolean currentButtonState = LOW;
boolean ledOn = false;
boolean motorOn = false;

long time = 0;
long time_0 = 0;

void setup()
{
  pinMode(switchPin, INPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(servoPin, OUTPUT);
  Serial.begin(9600);
}

/*------------------------------------------------------------*/
boolean debounce(boolean lastState)
{
  boolean currentState = digitalRead(switchPin);
  if (lastState != currentState)
  {
    delay(5);
    currentState = digitalRead(switchPin);
  }
  return currentState;
}
/*------------------------------------------------------------*/

void loop()
{
  currentButtonState = debounce(lastButtonState);
  if (lastButtonState == LOW && currentButtonState == HIGH && motorOn == false)
  {
    ledOn = !ledOn;
    if (ledOn) {
      motorOn = !motorOn;
    }
  }
  
  lastButtonState = currentButtonState;
  digitalWrite(ledPin, ledOn);
  
  time = 0;
  time_0 = millis();
  
  if (motorOn) {
    motorOn = false;
    while(time - time_0 <= 1000) {
      digitalWrite(servoPin,HIGH);
      delayMicroseconds(1600);
      digitalWrite(servoPin,LOW);
      delay(20);
      time = millis();
    }
  }
  digitalWrite(servoPin,HIGH);
  delayMicroseconds(1500);
  digitalWrite(servoPin,LOW);
  delay(20); 
}