Hello!
I'm new to Arduino and I'm learning things on my own with the help of people here on the forum and I'm trying to program a servo which a single button moves the servo from 0 to 90 degrees. But I'm getting an error and I can't find a fix, keep in mind I'm new to programming and I'm having a hard time. Thanks in advance!
<
#include <Servo.h>
Servo controlador_CoroaMotora; // create servo object to control a servo
const int buttonPin = 2; // the number of the pushbutton pin
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
controlador_CoroaMotora.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input
controlador_CoroaMotora.write(90); // sets the claw position to open
}
void loop() {
if ((buttonState == HIGH) && (controlador_CoroaMotora.read(90))){
controlador_CoroaMotora.write(0);
}
else if ((buttonState == HIGH) && (controlador_CoroaMotora.read(0))){
controlador_CoroaMotora.write(90);
}
}
The error message I'm getting is the following:
<
exit status 1
no matching function for call to 'Servo::read(int)'
The servo.read() function takes no argument. The Servo.read function returns the last position written (by the code) to the servo, not the current actual position of the servo.
Hi there!
I think I see the problem. You are trying to use the .read() function to check if the servo is at a certain degree position. This is not how that function works. Below is code from the Servo source file:
int Servo::read() // return the value as degrees
{
return map( this->readMicroseconds()+1, SERVO_MIN(), SERVO_MAX(), 0, 180);
}
According to this code, calling the function requires the argument field(the inside of the parenthesis) to be empty, meaning you cannot put anything there. When the function is called correctly, it will return the degree position that the servo was last sent to. Below is how to use the function properly in your code:
void loop()
{
int position = controlador_CoroaMotora.read();
buttonState = digitalRead(buttonPin); //NOTE this was not in your code that you posted, meaning the
//program will not check for the button state each time
if(buttonState == HIGH && position == 90)
{
controlador_CoroaMotora.write(0);
}
if(buttonState == HIGH && position == 0)
{
controlador_CoroaMotora.write(90);
}
}
Try this code, as well as your variable declarations and setup() portion and let me know how it works.
Good luck!
Thank you for the help, it works fine now!
Eduffleck:
Thank you for the help, it works fine now!
Why do you need to read the position that the servo was last sent to ?
After all, your code commanded to move there.
If you use a variable to hold the commanded servo position then you can use that value in any test of servo position.