Hello so Im doing a little project that just moves a servo motor based on the number given in the serial monitor and im getting this error exit status 1 no matching function for call to 'Servo::attach()'
How do I fix it?
full code:
#include <Servo.h>
int servo_motor = 9;
int state = 0;
void setup() {
Servo myservo;
myservo.attach();
myservo.write(state);
// Create serial object
Serial.begin(9600);
Serial.println(""); //im going to put something there
pinMode(servo_motor, OUTPUT);
}
void loop() {
// Have the arduino wait to recieve input
while (Serial.available() == 0);
// Read the input
int val = Serial.read() - '0';
if (val > 0) {
Serial.println("Servo motor has moved " val );
myservo.write(val);
}
}
Since you create the instance of the Servo class in setup(), the servo only exists in setup() (it is in scope only in setup()). Once setup() is finished the servo no longer exists.
Move the Servo myservo; to outside of setup() so that it is in global scope.
#include <Servo.h>
int servoPin = 9;
int state = 0;
Servo myservo;
void setup() {
myservo.attach(9);
myservo.write(state);
// Create serial object
Serial.begin(9600);
Serial.println("Use 1 to turn on the light and 0 to turn it off");
pinMode(servoPin, OUTPUT);
}
void loop() {
// Have the arduino wait to recieve input
while (Serial.available() == 0);
// Read the input
int state = Serial.read();
if (state > 0) {
Serial.println("Servo motor has moved " + state);
myservo.write(state);
}
}
Servo motor has moved
Servo motor has moved
Servo motor has moved
Servo motor has moved
Servo motor has moved
Servo motor has moved
Servo motor has moved