Cant get serial working right

That part states RS232. Are you using a serial-to-RS232 converter? Or did you directly connect the laser measurement system to the Mega?
Where do you get the communication parameters (baud rate etc) from?

Below can act as a framework to start testing the communication; it uses a simple state machine.

char command[] = "MS,0,01";
char terminator = '\r';

// timeout duration for receive from laser equipment
const uint32_t timeoutDuration = 5000;

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

void loop()
{
  // send command and receive reply
  if (fsmComms() == true)
  {
    // wait a bit
    delay(2000);
  }
}

/*
   Finite state machine for comms with laser equipment
   Returns:
    false while in progress
    true if full reply received or in case of timeout
*/
bool fsmComms()
{
  enum STATES
  {
    SEND,
    RECEIVE,
    TIMEOUT,
  };

  bool retVal = false;

  // state of state machine
  static STATES state = SEND;
  // start time for timeout
  static uint32_t timeoutStartTime;

  switch (state)
  {
    case SEND:
      Serial1.print(command);
      Serial1.write(terminator);
      timeoutStartTime = millis();
      state = RECEIVE;
      break;
    case RECEIVE:
      // if a timeout occurs
      if (millis() - timeoutStartTime >= timeoutDuration)
      {
        state = TIMEOUT;
      }
      // check if there is data received
      else if (Serial1.available())
      {
        // reset start time for timeut
        timeoutStartTime = millis();
        // read a byte
        char ch = Serial1.read();
        // print it
        if (ch < 0x10)
        {
          Serial.print("0");
        }
        Serial.print(ch, HEX);
        Serial.print(" ");
        // stop when we receive a terminator
        if (ch == terminator)
        {
          Serial.println();
          state = SEND;
          retVal = true;
        }
      }
      break;
    case TIMEOUT:
      Serial.println(F("[Timeout]"));
      retVal = true;
      state = SEND;
      break;
  }
  return retVal;
}

Tested with a Leonardo that echoes the received data back to the sending Mega.

For the final receive functionality I suggest that you study Robin's updated Serial Input Basics.

1 Like