2

I'm new to the Arduino world and am working on a sketch to run a servo up and down with a spdt switch. My code is :

include #include<Servo.h>
int pos = 0;

Servo myservo;
void setup() {
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  myservo.attach(9);
}
void loop() {
  if (digitalRead(2) == HIGH && pos < 180) {
    pos++;
    servo.write(pos);
    delay(15);
  }
  if (digitalRead(3) == HIGH && pos > 0) {
    pos--;
    servo.write(pos);
    delay(15);
  }
}

When I compile I get the "unexpected primary-expression before ';' token" error with exit status 1.

What am I doing wrong???

3
  • Use myservo instead of servo in the blocks (to start with :). Commented May 10, 2017 at 22:41
  • include #include<Servo.h> looks a bit screwy to me... ;) Commented May 10, 2017 at 22:44
  • You are looking at the last compiler error, but the first one is the most important. You can scroll up in that output window to find the first compiler error. Are you using Arduino IDE 1.8.2 with an Arduino Uno ? because I get a different compiler error. Commented May 10, 2017 at 23:12

1 Answer 1

4

1) You should be using:

myservo.write(pos);

instead of

servo.write(pos);

for all of your methods.

2) Change:

include #include<Servo.h>

to

#include <Servo.h>

This code only verifies when it is run on certain boards*, so make sure you are using one of those boards.Good luck and welcome to the Arduino world!:)

*Verify that your board will work, I know Mega, Uno and Nano will function properly.

P.s. Here is the whole code in correct format:

#include <Servo.h>

int pos = 0;

Servo myservo;
void setup() {
 pinMode(2, INPUT);
 pinMode(3, INPUT);
 myservo.attach(9);
}
void loop() 
{
  if ( (digitalRead(2) == HIGH) && (pos < 180)) {
    pos++;
    myservo.write(pos);
    delay(15);
  }
  if ( (digitalRead(3) == HIGH) && (pos > 0)) {
    pos--;
    myservo.write(pos);
    delay(15);
  }
}
2
  • I got it working on a NANO without the stacked parenthesis. My problem was I was trying to use an external servo library (not needed) and my USB cable was no good (power only) Commented May 12, 2017 at 0:07
  • @CSnyder okay! Glad to hear it ran on Nano, I will correct my answer, and overall that you got your project working. Good luck! Commented May 12, 2017 at 0:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.