Pages: [1]   Go Down
Author Topic: 2 "void loop"s?  (Read 207 times)
0 Members and 1 Guest are viewing this topic.
Philippines
Offline Offline
Newbie
*
Karma: 0
Posts: 26
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

for example:

Code:

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?
Logged

--Gin319

New Jersey
Online Online
Faraday Member
**
Karma: 67
Posts: 3677
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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).
Logged

Massachusetts, USA
Offline Offline
Tesla Member
***
Karma: 208
Posts: 8821
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
void loop() {
  if (x == 1) {
    nextchunkofcode(); //call next loop}

  //main code here
  }
}

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

Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Philippines
Offline Offline
Newbie
*
Karma: 0
Posts: 26
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:

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?
Logged

--Gin319

Saskatchewan
Offline Offline
Sr. Member
****
Karma: 19
Posts: 364
When the going gets weird, the weird turn pro. - Hunter S. Thompson
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Pages: [1]   Go Up
Jump to: