So, let me start by stating two things:
1- First ever post here.
2- Not sure if this is the right place to ask about this, I'm sorry if it's not.
OK now, onto the problem:
I'm a newcomer to Arduino, and I'm testing a basic setup of a servo motor controlled with a push button. Basically what I want is the servo to move to position 180 when the pushbutton is pressed once, and then move back to 0 when the button is pressed again.
The code for it, is this:
#include <Servo.h>
Servo myservo;
int val;
int buttonState = 0;
int lastButtonState= 0 ;
int buttonPin = 2;
int dir = 1;
int ledPin = 13;
int counter = 0;
int lastDebounceTime = 0;
int debounceDelay = 15;
String logMsg = "";
void setup() {
myservo.attach(9);
pinMode(buttonPin, INPUT);
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
myservo.write(0);
}
void loop() {
int reading = digitalRead(buttonPin);
if(reading != lastButtonState) {
lastDebounceTime = millis();
}
if ( (millis() - lastDebounceTime) > debounceDelay) {
if(reading != buttonState) {
buttonState = reading;
if(buttonState == HIGH) {
dir = 1;
counter++;
} else {
dir = 0;
}
delay(15);
}
if(counter % 2 ) {
digitalWrite(ledPin, HIGH);
while(val < 180) {
val+= 2;
myservo.write(val);
delay(15);
}
} else {
digitalWrite(ledPin, LOW);
while(val > 0) {
val -= 2;
myservo.write(val);
delay(15);
}
}
}
lastButtonState = reading;
}
My problem is that this works sometimes, and some other times it doesn't, and by doesn't I mean, the servo might stop mid turn and go back, or even go all the way to 180 and then instantly go back to 0 without me pressing the button.
I've been developing for more than 10 years, so I know my code, I'm assuming something in my hardware setup is generating some sort of random signal which triggers this behavior?
The setup is basically the combination of the servo tutorial and the pushbutton tutorials found on this site.
So does anyone have any ideas on what I might be doing wrong that would cause this behavior?
Thanks so much!