Hi! I'm very new to Arduino. I was wondering if I could get and help with looping certain lines of code. My project is a robotic arm. I have thes
e 3 lines of code:
Basically, it just tells the servo to move one degree. This is just so its slowed and doesn't flip the whole robot. The problem is that I have to repeat these 3 lines of code 45 times to get to the desired angle. My main question is if there is a simpler why to repeat this 45 times, instead of using 135 lines of code, for 1 servo. I have to do it like 3 more times. Feel free to criticize my code, it would even help if you did.
does not compile..
function name servo() is the same as name of your servo..
and did you notice how read changes color, use a different name for you variable, like myRead..
but yes, if it did compile, would not do what you want..
a for loop is good when you know exactly how many iterations (steps) you need..
a while loop is good when you don't know how many iterations but know the final goal..
and don't forget, you're already in a big loop called "loop()"..
a for would look like this..
//iterate 45 times..
for (int i = 0; i < 45; i++){
servo.write(servoPos);
servoPos--;
delay(30);
}
a while loop like this..
//iterate till destination is reached..
while (servoPos != destinationPos)
{
servo.write(servoPos);
if (servoPos>destinationPos) {servoPos--;} else{ servoPos++;}
delay(30);
}
and finally, using delay can be bad as it will hold up your main "loop()" unit it finishes..
the more delays you use the harder it will be to not use them..
this is why I showed the asynchronous (stepping) approach at first, it would be better if you can grasp it..
I have this now, and added a switch instead of adding it later in the project.
#include <Servo.h>
//--------------------------------------------------------------------------------------------------------------------------
Servo servo;
int read;
//--------------------------------------------------------------------------------------------------------------------------
void setup() {
servo.attach(13);
pinMode(2, INPUT_PULLUP);
servo.write(90);
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
void loop(){
read = digitalRead(2);
if (0 == read){
for (int i = 90; i >= 45; i--){
servo.write(i);
delay(50);
}
// This makes it not return to 90.
for (int i = 45; i <= 45; i = 45){
servo.write(i);
}
}
}