Go Down

Topic: 2 "void loop"s? (Read 247 times) previous topic - next topic

Gin319

Is it possible to have 2 loops that can be chosen to run in an arduino code?

for example:

Code: [Select]


void loop()

{ if x == 1
{ nextchunkofcode() //call next loop}

//main code here}

void nextchunkofcode()
{
//another chunk of code

a = 1;
b = 2;

}



Also, will the values that you obtained in the nextchunkofcode loop be saved in the main RAM and can be used in the main loop loop?
--Gin319

wildbill

You can call as many functions from the loop function as you like. In your example you could choose which one to call based on the value of your x variable. If you want to be able to share variables between these functions, you will either have to pass them as parameters, probably as references, or more simply, make them global (declare them outside any function).

johnwasser

Yes, you can define functions and call them from other functions, including loop().

If a variable is defined outside of any function it is "global" and shared across all functions in that file.  If its value is set in one function the new value will be seen in other functions.

Code: [Select]

void loop() {
 if (x == 1) {
   nextchunkofcode(); //call next loop}

 //main code here
 }
}

void nextchunkofcode() {
//another chunk of code
 a = 1;
 b = 2;
}
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Gin319

Hmmm... Thanks for your replies! I was planning something like this:

Code: [Select]


void setup() {

int x = 0;
int a = 0;
int b = 0;
int y = 0;
}


void loop() {
  if (x == 1) {
    nextchunkofcode(); //call next loop}

  //main code here

if y == some value obtained from nextchunkofcode() //use from nextchunkofcode()


  }
}

void nextchunkofcode() {
//another chunk of code
  a = 1;
  b = 2;

y = analogRead(pin);

}

Would this possibly work?
--Gin319

Jimmy60

Would this possibly work?

Not with the variables declared inside setup(). They are scoped only to setup(). Move them to before setup() making them global in scope. Global means available everywhere.

Go Up