Hello, I'm a beginner with arduino and I'm currently doing a project with a servo motor and two buttons. The code doesn't display any errors, but the way the servo spins doesn't change when variables like the ending position, step value or delay are changed. Currently, when a button is pressed it goes from the position of the servo when the board is reset (I assume that's 0) to 90 degrees at the same speed each time. Is there anything wrong with my code that could be causing this? Or should I be looking for hardware problems? The servo I'm using didn't have problems with different code, and I have been successful in editing these variables with good results in earlier projects.
#include <Servo.h>
Servo turn;
// constants won't change. They're used here to set pin numbers:
const int ledPin = 13; // the number of the LED pin
const int buttongreen = 8; // the number of the pushbutton pin
const int buttonred = 4; // the number of the pushbutton pin
// variables will change:
int buttonStategreen = 0;
int buttonStatered = 0;
int posg = 0;
int posr = 0;
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttongreen, INPUT);
pinMode(buttonred, INPUT);
turn.attach(7); // attaches the servo on pin 9 to the servo object
}
void loop() {
// read the state of the pushbutton value:
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (digitalRead(buttongreen) == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
for (posg = 0; posg <= 20; posg -= 0.5) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
turn.write(posg); // tell servo to go to position in variable 'pos'
delay(500); // waits 15ms for the servo to reach the position
}
}
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
else if (digitalRead(buttonred)== HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
{
for (posr = 0; posr <= 10; posr -= 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
turn.write(posr); // tell servo to go to position in variable 'pos'
delay(1); // waits 15ms for the servo to reach the position
}
} }
else if (digitalRead(buttonred)== LOW and digitalRead(buttongreen)== LOW) {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}