Hello
I am Creating an Arduino sketch that rotates the servo motor from 0 to 90 degrees if the pushbutton is pressed an even number of times; otherwise, it rotates from 180 degrees to 90 degrees. With a 10o step size and a 0.5sec delay between successive angles, the rotation will be gradual.
if I don't use while loop it works but rotates only once, and if I add while loop it doesn't work
can anyone tell me what I am doing wrong here
// C++ code
//
#include<Servo.h>
int button = 5;
int pbs; //previous button state
int cbs; //current button state
int count=0;
Servo myservo;
int pos;
void setup()
{
myservo.attach(10);
pinMode(button, INPUT);
cbs = digitalRead(button);
}
void loop()
{
pbs = cbs;
cbs = digitalRead(button);
if (pbs == HIGH && cbs == LOW)
{
count++;
if ((count%2)!= 0)
{
while(pbs == LOW && cbs == HIGH){
for(pos=0; pos<=90; pos+=10)
{
delay(500);
myservo.write(pos);
}
}
}
else
{
while(pbs == HIGH && cbs == LOW){
for(pos=180; pos>=90; pos-=10)
{
delay(500);
myservo.write(pos);
}
}
}
}
}
This is what I understood, for this code I have to double-tap the push button to go next stage, and it works when the servo is in the middle of the action.
but still can't figure it out single tap
// C++ code
//
#include<Servo.h>
int button = 5;
int pbs; //previous button state
int cbs; //current button state
int count=0;
Servo myservo;
int pos;
void setup()
{
myservo.attach(10);
pinMode(button, INPUT);
cbs = digitalRead(button);
}
void loop()
{
pbs = cbs;
cbs = digitalRead(button);
if (pbs == HIGH && cbs == LOW)
{
count++;
if ((count%2)!= 0)
{
while(digitalRead(button) != pbs && digitalRead(button) == cbs){
for(pos=0; pos<=90; pos+=10)
{
delay(500);
myservo.write(pos);
if (digitalRead(button) == pbs && digitalRead(button) != cbs){
break;
}
}
}
}
else
{
while(digitalRead(button) != pbs && digitalRead(button) == cbs){
for(pos=180; pos>=90; pos-=10)
{
delay(500);
myservo.write(pos);
if (digitalRead(button) == pbs && digitalRead(button) != cbs){
break;
}
}
}
}
}
}