ESP32 Serial Kommunikation mit Arduino Uno (GRBL)

Moin @anton_pro ,

bin kein Fan von if-else-if-else-if ... :wink:

Würde das so lösen (nur mal umgeschrieben, nicht getestet):

void ReceivedGCodeData(uint8_t *payload, size_t length)
{
  // Tokenize the payload into lines
  char *token;
  char *saveptr;
  token = strtok_r((char *)payload, "\n", &saveptr);
  while (token != NULL)
  {
    byte mode = 0;
    if (strcmp(token, "M7") == 0) { mode = 1; }
    if (strcmp(token, "M8") == 0) { mode = 1; }
    if (strcmp(token, "M2") == 0) { mode = 1; }
    if (strncmp(token, "G1", 2) == 0) { mode = 1; }
    if (strncmp(token, "G0", 2) == 0) { mode = 1; }
    if (strcmp(token, "G21") == 0) { mode = 1; }
    if (strcmp(token, "G90") == 0) { mode = 1; }
    if (strcmp(token, "F1000") == 0) { mode = 1; }
    if (mode == 1) { gcodeQueue.push(String(token));}
    token = strtok_r(NULL, "\n", &saveptr);
  }
}

Wenn noch weitere Befehle auszuwerten sein sollten, würde es sich ggf. anbieten, diese in einem Array zu speichern und in einer Schleife abzuarbeiten:

Beispielsketch
/*
  Forum: https://forum.arduino.cc/t/esp32-serial-kommunikation-mit-arduino-uno-grbl/1239346
  Wokwi: https://wokwi.com/projects/393623376239161345

  ec2021

*/

struct tokenStruct {
    char name[8];
    byte num;
};

const tokenStruct tokens[] = {
  {"M2",0},
  {"M7",0},
  {"M8",0},
  {"G0",2},
  {"G1",2},
  {"G21",0},
  {"G90",0},
  {"F1000",0},
};
const int noOfTokens = sizeof(tokens)/sizeof(tokens[0]);

void setup(){
  Serial.begin(115200);
  check("M1");
  check("M2");
  check("M21");
  check("G0");
  check("G012345");
  check("F1000");
}

void loop(){
}

void check(char * line){
  Serial.print(line);
  if (isValid(line)) {
      Serial.println(" is valid");
  } else {
      Serial.println(" is not valid");
  }
}

boolean isValid(char * token){
  for (int i = 0; i<noOfTokens;i++){
    if (tokens[i].num == 0){
      if (strcmp(token,tokens[i].name) == 0) {
        return true;
      }
    } else {
      if (strncmp(token,tokens[i].name, tokens[i].num) == 0) {
        return true;
      }
    }
  }
  return false;
}

Zum Testen bei Wokwi: https://wokwi.com/projects/393623376239161345

Bei void sendNextGCodeCommand() findet sich ein delay(200). Ist das erforderlich, wenn der Sketch eh auf eine Ok-Rückmeldung wartet? U.U. verlängert das nur unnötig den Transfer ..

void sendNextGCodeCommand()
{
  if (!waitingForOk && !gcodeQueue.empty())
  {
    int packetSize = 2; // Number of lines to send at once
    for (int i = 0; i < packetSize; i++)
    {
      if (!gcodeQueue.empty())
      {
        String command = gcodeQueue.front();
        gcodeQueue.pop();
        Serial.println("Sending GCode: " + command);
        Serial2.println(command);
      }
      else
      {
        break;
      }
    }
    waitingForOk = true;
    // +++++++++++++ Warum hier ein delay, wenn die Software eh auf ein Ok wartet? ++++++++++++
    delay(200);
  }
}

Viel Erfolg!
ec2021