0

Hi programming in arduino, I am trying to get a nested for loop inside a for loop with industrial servo which used PUL +- DIR+- (bought motor off amazon).

My goal is to get the puls delay to increase. I have a sensor attached that I want the servo to turn on when triggered.

So the sensor will get triggered and the the servo will start off fast and get slower up to 255 micros second delay.

example:

int sensor = 26;
int PUL = 23; //define Pulse pin
int DIR = 25; //define Direction pin

void setup() {
  pinMode(sensor, INPUT);
  Serial.begin(115200);
  pinMode (PUL, OUTPUT);
  pinMode (DIR, OUTPUT);
}

void loop() {
  int sen = digitalRead(sensor);
  if (sen == HIGH) {
    Serial.println("HIGH");
    delay(1000);
     for (int i=0; i<500; i++)    
  {
      for( int x=0; x<255; x++){

    digitalWrite(DIR,LOW);
    digitalWrite(PUL,HIGH);
    Serial.print("i = ");
    Serial.println(i);
    Serial.print("x = ");
    Serial.println(x);
    delayMicroseconds(x);
    digitalWrite(PUL,LOW);
    delayMicroseconds(x);
  }}
  } else if (sen == LOW) {
    Serial.println("LOW");
    delay(1000);
    } else {
    Serial.println("ERROR");
  }
}

EDIT

I am trying to nest a FOR loop inside a FOR loop What I want to do is get x to increase with i until x is 255 then I will continue unit i reaches 500. Right now x goes 0-255 and then i increase by 1. I need the value of x to increase along side with i until 255

for (int i=0; i<500; i++) { 
  for( int x=0; x<255; x++){ 
  digitalWrite(DIR,LOW);
  digitalWrite(PUL,HIGH);
  Serial.print("i = ");
  Serial.println(i);
  Serial.print("x = ");
  Serial.println(x);
  delayMicroseconds(x);
  digitalWrite(PUL,LOW);
  delayMicroseconds(x); }
}
1
  • 2
    it is unclear what you have, how it is connected and what you are trying to do exactly
    – jsotola
    Commented Jan 28, 2020 at 21:26

1 Answer 1

1

Do you want i and x to increment at the same rate 0-255 then x to remain 255 while i increases to 500?

this should do what you want. i and x increase together until x reaches 255 then it wont increment.

int x=0;
for (int i=0; i<500; i++) { 

  digitalWrite(DIR,LOW);
  digitalWrite(PUL,HIGH);
  Serial.print("i = ");
  Serial.println(i);
  Serial.print("x = ");
  Serial.println(x);
  delayMicroseconds(x);
  digitalWrite(PUL,LOW);
  delayMicroseconds(x); }

   if(x<=255){
        x++;
   }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.