Serial port capture error

Hello, I'm trying to receive a string through the serial port, but I can't capture it, there is simply no data, I don't understand what could be the problem, can someone tell me how to correct this so that it works?.

I need the capture routine to be in setup but not in loop

This is the string I need to capture:

+DATAFRAME:frames:20,data_len:2676,cache_len:3384,OK\r\n\r\n

This is my code:

String received;

void receive(){
  while (Serial.available() > 0) {
    received += (char)Serial.read();
    if (received.endsWith("OK\r\n\r\n")) {
      Serial.println("answer: " + received);
      break;
    }
  }
}

void setup() {
  Serial.begin(9600);
  Serial.println("AT+DATAFRAME?");
  receive();
}

void loop() {
}

If there's no data to read, receive() is going to return immediately.
You should wait for data to be available, before calling receive()

I suggest that you print the received characters (preferably in hex) to see what you exactly receive.
Something like

void receive()
{
  while (Serial.available() > 0)
  {
    char c = Serial.read();
    if (c < 0x10)
    {
      Serial.print("0");
    }
    Serial.print(c, HEX);
    Serial.print(" ");

    received += c;
    if (received.endsWith("OK"))
    {
      Serial.println("received: " + received);
      break;
    }
  }
}

I already did the test as you suggest but still nothing is received, no character is printed

Because the function has already returned, I imagine.

I don't understand what you mean, can you be more specific please?

Please could some of you be so kind as to try it on your Arduino, because I can't get this program to run.

You don't wait at all, so there's nothing there and you return.

Try

void receive(){
  while (1) {   // basically forever... 
    if (Serial.available() > 0) {
      received += (char)Serial.read();
      if (received.endsWith("OK\r\n\r\n")) {
        Serial.println("answer: " + received);
        break;
      }
    }
  }
}

Sry, can't test it from here. One reason it might not work too good is the awfully specific ending condition you have there.

Perhaps some other test, or a way to break out of the forever loop like too much time has passed or N number of characters received but no joy yet on the OK thing should be in there.

HTH

a7

I'm not sure I can, but here goes.
In setup(), you queue-up a string "AT+DATAFRAME?" for transmission, then immediately, you call the function "receive()".
First, this function looks to see if there is something in the Serial receive buffer to read.
Almost certainly, there isn't, so the function "receive()" returns, the the function "setup()" returns, and the function "loop()" gets called, and does nothing.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.