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 :). – Mikael Patel May 10 '17 at 22:41
  • include #include<Servo.h> looks a bit screwy to me... ;) – Majenko May 10 '17 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. – Jot May 10 '17 at 23:12
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) – C Snyder May 12 '17 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! – L. Paw May 12 '17 at 0:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.