Hi everyone,
Currently I'm working on a project and have been stuck on programming for days and I desperately need help. I think its a simple program but can someone please help me. PS I'm not good in programming.
I need my servo to rotate clockwise and counter-clockwise in a certain speed and angle. A switch button is included to change to mode with every press.
Example:
Button switch is pressed Once, servo rotate with speed "A" and angle of 10 degrees
Twice, servo rotate with speed "B" and angle of 60 degrees
Thrice, servo rotate with speed "C" and angle of 50 degrees
Fourth, everything starts from the beginning, with speed "A" and angle of 10 degrees
Here's a copy of my codes
#include<Servo.h>
Servo myservo;
int switchState = 0;
int pos = 0;
int val;
int lastswitchState = 0; // previous state of the button
int switchcount = 0;
void setup()
{
myservo.attach(9);
Serial.begin(9600);
pinMode(2,INPUT);
}
void loop()
{
switchState = digitalRead(2);
if (switchState != lastswitchState)
{
if (switchState == HIGH)
{
switchcount++;
for(pos = 0; pos < 10; pos += val) // goes from 0 degrees to 10 degrees
{
val = map(val, 0, 1023, 1, 25);
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(30); // time for the servo to reach the position
}
for(pos = 10; pos>=1; pos -= val) // goes from 10 degrees to 0 degrees
{
val = map(val, 0, 1023, 1, 25);
myservo.write(pos);
delay(30);
}
}
}
if (switchState == HIGH)
{
switchcount++;
for(pos = 0; pos < 60; pos += val) // goes from 0 degrees to 60 degrees
{
val = map(val, 0, 1023, 1, 25);
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(50); // time for the servo to reach the position
}
for(pos = 60; pos>=1; pos -= val) // goes from 60 degrees to 0 degrees
{
val = map(val, 0, 1023, 1, 25);
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(50); // waits 15ms for the servo to reach the position
}
}
if (switchState == HIGH)
{
switchcount++;
for(pos = 0; pos < 50; pos += val) // goes from 0 degrees to 50 degrees
{
val = map(val, 0, 1023, 1, 25);
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(100); // time for the servo to reach the position
}
for(pos = 50; pos>=1; pos -= val) // goes from 50 degrees to 0 degrees
{
val = map(val, 0, 1023, 1, 25);
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(100); // waits 15ms for the servo to reach the position
}
}
if(switchState != lastswitchState)
{
if(switchState == 1)
{
switchcount = switchcount +1;
}
}
lastswitchState = switchState;
delay(200);
}
here's an attached file of the program
Thanks everyone for the time and kind help
BETA_testing_Heart_Beat_Simulation.ino (2.82 KB)