Send AT commands to ESP8266 with Arduino

I have an Arduino UNO wired up to my ESP8266 like so:

D10 → RX
D9 → TX

When I have this sketch uploaded to the Arduino everything works fine:

#include <SoftwareSerial.h>

SoftwareSerial ESP(9, 10); //TX, RX

void setup () {
  ESP.begin(115200);
  Serial.begin(115200);
  Serial.println("=ESP8266 Test=");
}

void loop () {
  unsigned long curMillis = millis();
  
  while (ESP.available()) {
    Serial.write(ESP.read());
  }

  while (Serial.available()) {
    ESP.write(Serial.read());
  }
}

When I make it so that the Arduino sends the AT command every five seconds as test, it doesn’t work:

#include <SoftwareSerial.h>

SoftwareSerial ESP(9, 10); //TX, RX

unsigned long prevMillis = 0;
const long waitMillis = 5000; //ms

void setup () {
  ESP.begin(115200);
  Serial.begin(115200);
  Serial.println("=ESP8266 Test=");
}

void loop () {
  unsigned long curMillis = millis();
  
  while (ESP.available() > 0) {
    Serial.write(ESP.read());
  }

  while (Serial.available() > 0) {
    ESP.write(Serial.read());
  }

  if (curMillis - prevMillis >= waitMillis) {
    prevMillis = curMillis;

    Serial.write("AT");
    // ESP.write("AT");
  }
}

I’ve tried both Serial.write and ESP.write and they just print out like so: ATATATATAT

How can I fix this?

EDIT: using ESP.println(“AT”) worked…

superhb:
EDIT: using ESP.println(“AT”) worked…

Yes, what you couldn’t see is that when you enter some text in the Serial Monitor it adds the line ending but your second sketch didn’t do that so the command was not recognized by the ESP8266.

"AT\r\n" change your code to this