What is a correct way of sending request and then reading data by Serial?

I'm trying to read a message from GSM (SIM 300). I send a command but the answer is about 150 characters so I get buffer overflow.
Here is what I'm doing:

void loop()
{
	Serial1.println("AT+CMGR=1");
	delay(100);
	while (Serial1.available())
	{
		Serial.write(Serial1.read());
	}

I do get overflow here. If I remove Serial1.println("AT+CMGR=1") and just send data from my laptop and read it then everything is ok.

I send a command but the answer is about 150 characters so I get buffer overflow.

Why are you sending that command, unconditionally, on EVERY pass through loop()?

At most, you should only send that command when the response from the previous command has been fully received.

You seem to think that the entire 150 character response will arrive within the 1/10th of second that you are waiting. That is unlikely.

It should read while Serial1.available() and it should be >0 untill all 150 bytes are received. I also tried to put delay(1000) at the end. All the same.

It should read while Serial1.available() and it should be >0 untill all 150 bytes are received.

No. That is not true. Imagine that you are reading over my shoulder as I type slowly. There are some number of characters that you have not yet read, but, at some point, you will read everything I have typed, even though I haven't finished a paragraph, or even a sentence (or word). If you assume, having read everything I typed slowly, that that was the complete message, you'd be wrong.

If you close your eyes for 100 milliseconds, while I hunt and peck away, I might have typed more than 64 characters while you were napping. Those extra characters are then lost.

So what whould be a correct way of reading without buffer overflow?

On each pass through loop(), read all the data that is available. Get rid of all calls to delay().

You really need to KNOW when the end of a response has arrived, so you don't send another command until that has happened.

Here is what I have for reading now. Still not reading up to the end.

char* sim300::read(char* buf, uint16_t timeout)
{
	buf[0] = 0;
	size_t len = 0;
	char* pointer = buf;
	uint32_t tick = millis();
	while (millis() - tick <= timeout)
	{
		while (gsm->available())
		{
			pointer += gsm->readBytes(pointer, gsm->available());
			tick = millis();
		}
	}
	*pointer = 0;

and now I'm not sending until it reads out everything. Timeout is 1000

Problem solved. I had '\0' bytes in the message and that was hiding the rest of the message when I printed it out. ]:smiley: