C++ Esp32 函数式无限循环

C++ Esp32 functional infinite loop

所以我有这样的代码:

void B();
void C();

void A() {
  Serial.println("Looping");
  B();
}

void B() {
  C();
}

void C() {
  A();
}


void setup() {  
  Serial.begin(115200); 
  A();
}

void loop() {
 
};

它工作得很好,但是当我想添加一个条件时,像这样:

bool flag = false;

void B();
void C();

void A() {  
  Serial.println("Looping");
  if(flag)
    B();
  else 
    C();
}

void B() {
  flag = false;
  A();
}

void C() {
  flag = true;
  A();
}


void setup() {  
  Serial.begin(115200); 
  A();
}

void loop() {
 
};

一段时间后,我的 esp32 抛出回溯并重新启动:

Guru Meditation Error: Core  1 panic'ed (Unhandled debug exception)
Debug exception reason: Stack canary watchpoint triggered

我需要某种解决方案 运行 B()C() 并“忘记” A() body,因为我理解这个问题。

UDP 这只是真实代码的框架,我正在使用 FreeRTOS(xTaskCreate,...)来 运行 逻辑, 我有一个想法:

1) Create 2 Tasks (one of them will be running) 
2) Later pass the function I want to call, delete running
3) Such way by switching tasks it should work

我在一个项目中有这样的逻辑:


void B();
void C();

void A() {    
  if(server.connect())
    while(server.isConnected()) {
      //makeUpdate, receive new messages
    }

  //  as it fails, make reconnect
  //check wifi connection
    if(wifi)
      B();
    else 
      C();  
}

void B() {
  // Update Connection With Wifi
  // Go back to connect
  A();
}

void C() {
  // Update Connection With Gprs
  // Go back to connect
  A();
}


void setup() {  
  Serial.begin(115200); 
  A();
}

void loop() {
 
};

像这样调用函数会导致无限递归,耗尽堆栈并使整个程序崩溃。

您可以调用内部的所有函数 loop() 和其他函数 return 接下来应该调用哪个函数。

char A() {
  Serial.println("Looping");
  if(flag)
    return 'B';
  else
    return 'C';
}

char B() {
  // Update Connection With Wifi
  // Go back to connect
  return 'A';
}

char C() {
  // Update Connection With Gprs
  // Go back to connect
  return 'A';
}

void setup() {
  Serial.begin(115200);
}

void loop() {
  static char next_function = 'A';
  switch(next_function) {
    case 'A': next_function = A(); break;
    case 'B': next_function = B(); break;
    case 'C': next_function = C(); break;
  }
}