Hi guys!
I would like to make next –
When I press the button, servo goes from 180 degree to 0, and returns to 180 (actually 179, because as I understood, constrain will return to max position only if it is lower than start position), just one time.
I was trying to figure out how to do this… So, is this correct way?
I'm not at home at this moment so I can't try it directly on board...
Thanks!
No. If the Arduino is only supposed to move the servo through its range of motion, and back, two for loops are all that is needed.
You might want to look at the state change detection example, to see how to make the code do something when the switch BECOMES pressed, rather than IS pressed.
void loop(){
buttonState = digitalRead(buttonPin);
if ((buttonState == HIGH) && (oldButtonState == LOW)) {
for(position = 0; position <=180; position += 1) // position never reaches 180 here if you type <180
{
myservo.write(position); // in the example code there is a delay here
}
for(position = 180; position>=0; position-=1) // you mistyped pos here
{
myservo.write(position); // also a delay here in the example code
}
}
oldButtonState = buttonState;
}
Since you write 180 to your servo motor in the setup, I think
you should swap the for statements. 180 first from 180 to 0 then 0 back to 180
if ((buttonState == HIGH) && (oldButtonState == LOW)) {
for(position = 0; position <=180; position += 1) // position never reaches 180 here if you type <180
{
myservo.write(position); // in the example code there is a delay here
}
for(position = 180; position>=0; position-=1) // you mistyped pos here
{
myservo.write(position); // also a delay here in the example code
}
}
oldButtonState = buttonState;
}
Since you write 180 to your servo motor in the setup, I think
you should swap the for statements. 180 first from 180 to 0 then 0 back to 180
Thank's siutoejai, I've overlooked that.
It works just like I wanted!
Cheers mate!