Button and Servo

Hi,
I'm new to Arduino and programming.
I tried making a servo move 90 degrees and then go back to position
when I pressed down a pushbutton, but a message saying "Error compiling for short Arduino / Genuino Uno." comes up. There is probably a lot of things that I have done wrong I guess. I took a code from a website and changed it.

Heres the code:

const int buttonPin = 2;
int buttonState = 0;
#include <Servo.h>

Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0; // variable to store the servo position

void setup() {
buttonState = digitalRead(buttonPin);
myservo.attach(9); // attaches the servo on pin 9 to the servo object

if (buttonState == HIGH) {
for (pos = 0; pos <= 90; pos += 1) { // goes from 0 degrees to 90 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(0); // waits 10s for the servo to reach the position
}
for (pos = 90; pos <= 0; pos -= 1) { // goes from 90 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(20); //
}
}
}

Hi, welcome to the forum! Before you make any more posts, please have a look at "How to use the forum" :slight_smile: Especially the part about code tags. And please edit your post to include it :slight_smile:

Also, great tip, that is NOT the whole error message. The whole error will try to tell you where that error is.

In this case it tells you your code misses a loop() function. Even though you don't want to use it, every sketch at least needs a setup() an a loop() function. Leave blank if you don't want to use it. But, in this case, I doubt you only want to move the servo once when you have the button presses when you power up the Arduino. So you need to split the code, things you want to happen once (like pinMode() and .attache()) go into setup(), rest in the loop() to be done/checked over and over.

One problem is that, unless you are holding the button down when you start the sketch, the 'if' won't trigger and your sketch will hit the end of the setup() function. Your sketch then runs the loop() function over and over.

You should put in a loop() function. You should probably move your big 'if' statement there so you have more than one chance to test the button pin.