Hi, I am pretty new to coding and Arduino I need help to make it in real life. I found this code. So if anyone can help it would be a real life saver.
Thank you
#include <Servo.h>
Servo myServo;
const int switchPin = 8;
int buttonState = 0;
int lastButtonState = 0;
int buttonPushCounter = 0;
void setup() {
// put your setup code here, to run once:
myServo.attach(4);
myServo.write(0);
Serial.begin(9600);
}
void push(){
myServo.write(90);
delay(250);
myServo.write(0);
}
void loop() {
// put your main code here, to run repeatedly:
buttonState = digitalRead(switchPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button went from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
} else {
// if the current state is LOW then the button went from on to off:
Serial.println("off");
}
// Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state, for next time through the loop
lastButtonState = buttonState;
// turns on the LED every four button pushes by checking the modulo of the
// button push counter. the modulo function gives you the remainder of the
// division of two numbers:
if (buttonPushCounter % 2 == 0) {
push();
}
}
It is usually a bad idea to power the servo from the Arduino 5V or USB power. Use an external supply capable of supplying the servo stall current. Connect the grounds.
buttons are typically connected between the pin and ground, the pin configured as INPUT_PULLUP to use the internal pullup resistor which pulls the pin HIGH and when pressed, the button pulls the pin LOW.
look this over (a bit simpler)
# include <Servo.h>
Servo myServo;
const int SwitchPin = 8;
byte butLst;
int butCnt;
void setup ()
{
Serial.begin (9600);
pinMode (SwitchPin, INPUT_PULLUP);
butLst = digitalRead (SwitchPin);
myServo.attach (4);
}
void loop ()
{
byte but = digitalRead (SwitchPin);
if (butLst != but) { // change
butLst = but;
delay (20); // debounce
if (LOW == but) { // press
butCnt++;
Serial.println (butCnt);
if (butCnt % 2)
myServo.write (90); // odd
else
myServo.write (0); // even
}
}
}
I tried this code but I have to press the button once to go to 90 degrees and then again to go back to 0. I want all that to be in one press, not two. I also want to make the servo move faster. If you could help that would be great.
What is supposed to make it go back to zero? Un-pressing the button? Waiting for a certain tie after you pushed the button? Waiting for a certain time after you released the button?