Serial.readBytesUntil part of input stays in buffer

In setup I use Serial.readBytesUntil to get nameServer and the second to get accessToken.

Serial.println("serverName: ");
Serial.readBytesUntil(10, serverName, 18);
Serial.println("accessToken: ");
Serial.readBytesUntil(10, accessToken, 18);

I have set Serial.setTimeout(10000)

If I make much longer input and press enter, the 18 characters goes to serverName and the rest of buffer goes to accessToken without any pause. It is often longer than 18 characters.

What should I do to avoid this situation? I can’t use in loop

Please post a complete program that exhibits the problem.

if (Serial.available()) {
 Serial.println("The server name is too long);

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.


This is in setup. Not in loop.

#include <ArduinoJson.h>
#include "FS.h"

#define FILE_CONFIG  "/config.json"
const byte numChars = 32;
char serverName[numChars];
char accessToken[numChars];
boolean newData = false;

bool saveConfig() {
  DynamicJsonBuffer jsonBuffer;
  JsonObject& json = jsonBuffer.createObject();
  Serial.println("Podaj serverName");
  Serial.readBytesUntil('\n', serverName, 18);
  Serial.println("Podaj accessToken");
  Serial.readBytesUntil('\n', accessToken, 18);
  json["serverName"] = serverName;
  json["accessToken"] = accessToken;

  File configFile ="/config.json", "w");
  if (!configFile) {
    Serial.println("Failed to open config file for writing");
    return false;

  return true;

void setup() {
  Serial.setTimeout(10000); // czas na wpisanie SSID i password
  Serial.println("Mounting FS...");

  if (!SPIFFS.begin()) {
    Serial.println("Failed to mount file system");

  if (!saveConfig()) {
    Serial.println("Failed to save config");
  } else {
    Serial.println("Config saved");

  if (!loadConfig()) {
    Serial.println("Failed to load config");
  } else {
    Serial.println("Config loaded");

void loop() {

I dont know how but solution given by Juraj works. Long way before me :slight_smile: