How to work with subroutines?


hello, need on using goto statement. doing traffic light signal.my program supposed go line if switch button on.here code;

code: [select]
int trafficlights1[] = {2,3,4,5}; // red, yellow, green, pedestrians led pins
int trafficlights2[] = {6,7,8,9}; // red, yellow, green, pedestrians led pins
int situations = 4;
int duration[] = {8000,3000,10000,3000}; // duration of each situation
long previouscars = 0;
long previouspeds = 0;
long interval = 300; //blink interval pedestrians
int ledstate = low;
int state;
int = 0;

void setup()
{
  for(int = 0; < 4; i++) {
  pinmode(trafficlights1[i], output);
  pinmode(trafficlights2[i], output);

  }
serial.begin(9600);
}
 
void loop()
{
unsigned long currentmillis = millis();
if(currentmillis - previouscars < duration[i]) {
situation(i);
} else {
previouscars = currentmillis;
if(i >= situations) {
i = 0;
} else {
i++;
}
}
}

void activatetrafficlight1(string lights, int pedestrians)
{
for(int x = 0; x < 3; x++)

{
if(lights[x] == '0') state = low;
if(lights[x] == '1') state = high;
digitalwrite(trafficlights1[x], state);
}
if(pedestrians == 1) {
blinkped(trafficlights1[3]);
} else {
digitalwrite(trafficlights1[3], low);
}
}
 
void activatetrafficlight2(string lights, int pedestrians)
{
for(int x = 0; x < 3; x++)
{
if(lights[x] == '0') state = low;
if(lights[x] == '1') state = high;
digitalwrite(trafficlights2[x], state);
}
if(pedestrians == 1) {
blinkped(trafficlights2[3]);
} else {
digitalwrite(trafficlights2[3], low);

}
}
 
void situation(int i)
{
switch(i){
case 0:
activatetrafficlight1("100",1); // 100 means red on, yellow off, green off
activatetrafficlight2("001",0); // second parameter pedestrians
break; // 1 on , 0 off
case 1:
activatetrafficlight1("110",0); // 110: red on, yellow on, green off
activatetrafficlight2("010",0);
break;
case 2:
activatetrafficlight1("001",0);
activatetrafficlight2("100",1);
break;
case 3:
activatetrafficlight1("010",0);
activatetrafficlight2("110",0);
break;
}
}
 
void blinkped(int ped) {
       
unsigned long currentmillis = millis();
if(currentmillis - previouspeds > interval) {
previouspeds = currentmillis;
if (ledstate == low)
ledstate = high;
else
ledstate = low;
digitalwrite(ped, ledstate);
}
}

quote
i need on using goto statement
i think mean need in getting rid of gotos in code.  using them leads code hard maintain because hard follow logic.  never necessary.  instead call function perform actions when detect switch state has changed.

start editing post, selecting code , clicking code icon </> @ left of icons above editor window.  prevent code being interpretted html , being mangled now.


Arduino Forum > Using Arduino > Programming Questions > How to work with subroutines?


arduino

Comments