Servo Toggle Attempt.ino (499 Bytes)
i was attempting to run a program that made it so when i push the button once, the servo would move one way, and with a second push of the button, the servo would return to its original position, rotating back
ive been at this for hours browsing forums and trying to modify different examples of code with no luck, having the servo jitter was the furthest ive made it and this code provokes no response in the servo when the button is pressed
any help would be greatly appreciated, thanks!!
Please post your code in a reply to this topic, using code tags when you do
1 Like
consider
- need to attach servo to pin
- configure button as INPUT_PULLUP, connect button between pin and ground and test for LOW
- Capitalize Constants, not variables
#include "Servo.h"
Servo myservo;
int ServoPin = 3;
int servoPos = 0;
int ButtonPin = 2;
int buttonOld;
void loop ()
{
byte but = digitalRead (ButtonPin);
if (buttonOld != but) {
buttonOld = but;
delay (20); // debounce
if (LOW == but) { // button pressed
if (servoPos == 0)
servoPos = 180;
else
servoPos = 0;
Serial.println (servoPos);
myservo.write (servoPos);
}
}
}
void setup () {
Serial.begin (9600);
myservo.attach (ServoPin);
pinMode (ButtonPin, INPUT_PULLUP);
buttonOld = digitalRead (ButtonPin);
}
2 Likes
#include "Servo.h"
Servo myservo;
int ServoState=0;
int Servo=3;
int ButtonPin=2;
int ButtonNew;
int ButtonOld=1;
int dt=100;
void setup() {
Serial.begin(9600);
pinMode(Servo, OUTPUT);
pinMode(ButtonPin, INPUT);
}
void loop() {
ButtonNew=digitalRead(ButtonPin);
if(ButtonOld==0 && ButtonNew==1) {
if (Servo==0) {
myservo.write(180);
ServoState=1;
}
else{
myservo.write(0);
ServoState=0;
}
}
ButtonOld=ButtonNew;
delay(dt);
}
noobie to the interface on this and coding in general i think this is what you asked for sorry if it isnt-
Thanks! ill keep that in mind for the future, that ran and worked except for what i believe to be either a slow processor on the board im using(nano) or some wiring issues that caused it to be somewhat inconsistant when testing-
generally new to this i had an RFID switch on another nano powering a bunch and it has the same inconsistancy issue in which i can only chalk up to wiring-
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.