Serial communication only with serial monitor open

I can't get my ESP8266 to communicate with the Arduino Leonardo board , whithout opening the Serial Monitor.

My code is this :

//set pin numbers :
#define ledPin 13
#define ESP8266_CHPD 9
#define bufferSize 64

//Motor code
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
Adafruit_MotorShield AFMS = Adafruit_MotorShield(); 
Adafruit_DCMotor *motor1 = AFMS.getMotor(4);
Adafruit_DCMotor *motor2 = AFMS.getMotor(3);
Adafruit_DCMotor *motor3 = AFMS.getMotor(1);
Adafruit_DCMotor *motor4 = AFMS.getMotor(2);
bool reverse =false;
void moveForward(int s);
int speedo=255;
Serial_ & dbgTerminal = Serial;
HardwareSerial & espSerial = Serial1;

char ledState = HIGH;            

char buffer[bufferSize];

void setup() { 
 pinMode(ledPin, OUTPUT);  
 pinMode(ESP8266_CHPD, OUTPUT);
 digitalWrite(ESP8266_CHPD, HIGH);

 dbgTerminal.begin(9600); // Serial monitor
 espSerial.begin(115200); // ESP8266
 AFMS.begin();
 while (!dbgTerminal) { }
  // wait for serial port to connect. Needed for Leonardo only
 
 hardReset();
 delay(1000);

 clearSerialBuffer();
 //connect to the network
 connectWiFi("Bulaichi-netis", "19216811");
 //test if the module is ready
 //dbgTerminal.print("AT : ");
 dbgTerminal.println( GetResponse("AT",50) );
 //set the multiple connection mode
 //dbgTerminal.print(F("AT+CIPMUX=1 : "));
 dbgTerminal.println( GetResponse("AT+CIPMUX=1",50) );
 //set the server of port 80 check "no change" or "OK"
 //dbgTerminal.print(F("AT+CIPSERVER=1,8888 : "));
 dbgTerminal.println( GetResponse("AT+CIPSERVER=1,8888", 50) );
 //set time out
 //dbgTerminal.print("AT+CIPSTO=15 : ");
 dbgTerminal.println( GetResponse("AT+CIPSTO=15",50) );
 //print the ip addr
 //dbgTerminal.print(F("ip address : "));
 dbgTerminal.println( GetResponse("AT+CIFSR", 50) );
 delay(50);
 //dbgTerminal.println();
 dbgTerminal.println(F("Start Webserver"));
 
 digitalWrite(ledPin,ledState);  
}

void loop() {
 //for the motor
 //uint8_t i;
 // myMotor->run(FORWARD);
 //for (i=0; i<255; i++) {
 //  myMotor->setSpeed(i);  
 //  delay(10);
 //}
 //motor
 int ch_id, packet_len;
 char *pb;  
 espSerial.readBytesUntil('\n', buffer, bufferSize);
 
 if(buffer[0]!=NULL)dbgTerminal.println(buffer);
 
 if(strncmp(buffer, "+IPD,", 5)==0) {
   // request: +IPD,ch,len:data
   sscanf(buffer+5, "%d,%d", &ch_id, &packet_len);
   if (packet_len > 0)
   {
       pb = buffer+5;
       while(*pb!=':') pb++;
       pb++;
       dbgTerminal.print(*pb);
       dbgTerminal.println(*(pb+1));
       switch (*pb)
       {
         case 'g' : if(*(pb+1)== '1')
                       if (reverse == false)
                        moveForward(speedo);
                       else moveBackward(speedo);
                       else moveBackward(0);
         break;
         case '-' :if (reverse == false) reverse=true; else reverse =false; 
         break;
         case 'r':if(*(pb+1)== '1')
                     rotateRight(speedo);
                     else rotateRight(0);
         break;
         case 'l':if(*(pb+1)== '1')
                     rotateLeft(speedo);
                     else rotateLeft(0);
         break;
       }
       delay(10);
       clearSerialBuffer();
   }

 }
 clearBuffer();
}
void moveForward(int speedo)
{
    motor1->run(FORWARD);
    motor2->run(FORWARD);
    motor3->run(BACKWARD);
    motor4->run(BACKWARD);
    motor1->setSpeed(speedo);
    motor2->setSpeed(speedo);
    motor3->setSpeed(speedo);
    motor4->setSpeed(speedo);
    delay(10);
}
void moveBackward(int speedo)
{
    motor1->run(BACKWARD);
    motor2->run(BACKWARD);
    motor3->run(FORWARD);
    motor4->run(FORWARD);
    motor1->setSpeed(speedo);
    motor2->setSpeed(speedo);
    motor3->setSpeed(speedo);
    motor4->setSpeed(speedo);
    delay(10);
}
void rotateRight(int speedo)
{
    motor1->run(BACKWARD);
    motor2->run(FORWARD);
    motor3->run(BACKWARD);
    motor4->run(FORWARD);
    motor1->setSpeed(speedo);
    motor2->setSpeed(speedo);
    motor3->setSpeed(speedo);
    motor4->setSpeed(speedo);
    delay(10);
}
void rotateLeft(int speedo)
{
    motor1->run(FORWARD);
    motor2->run(BACKWARD);
    motor3->run(FORWARD);
    motor4->run(BACKWARD);
    motor1->setSpeed(speedo);
    motor2->setSpeed(speedo);
    motor3->setSpeed(speedo);
    motor4->setSpeed(speedo);
    delay(10);
}
// Get the data from the WiFi module and send it to the debug serial port
String GetResponse(String AT_Command, int wait){
 String tmpData;
 
 espSerial.println(AT_Command);
 delay(wait);
 while (espSerial.available() > 0 )  {
   char c = espSerial.read();
   tmpData += c;
   
   if ( tmpData.indexOf(AT_Command) > -1 )         
     tmpData = "";
   else
     tmpData.trim();       
         
  }
  return tmpData;
}

boolean hardReset() {
 String tmpData;

 digitalWrite(ESP8266_CHPD,LOW);
 delay(100);
 digitalWrite(ESP8266_CHPD,HIGH);
 delay(500);

 while ( espSerial.available() > 0 ) {
   char c = espSerial.read();
   tmpData +=c;
   dbgTerminal.write(c);
   if ( tmpData.indexOf("ready") > -1 ) {
     Serial.println("Ready");
     clearBuffer();
     return 1;
   } 
 }
 dbgTerminal.println();
}

void clearSerialBuffer(void) {
 while ( espSerial.available() > 0 ) {
   espSerial.read();
 }
}

void clearBuffer(void) {
 for (int i =0;i<bufferSize;i++ ) {
   buffer[i]=0;
 }
}
boolean connectWiFi(String NetworkSSID,String NetworkPASS) {
 
 //dbgTerminal.print("AT+CWMODE=1 : ");
 dbgTerminal.println( GetResponse("AT+CWMODE=1",1000) );
 
 String cmd = "AT+CWJAP=\"";
 cmd += NetworkSSID;
 cmd += "\",\"";
 cmd += NetworkPASS;
 cmd += "\"";

 dbgTerminal.print(cmd); 
 dbgTerminal.print(" : "); 
 dbgTerminal.println(GetResponse(cmd,8000));
}

It's because of this line:

 while (!dbgTerminal) { }

That causes the Leonardo to stay in that while() loop until the Serial Monitor is opened.

Debug output is very handy but it uses memory and slows your program down when you're not using it. The best way I've found to switch it on and off is this:

#define DEBUG false
#define dbgTerminal if(DEBUG)Serial

After adding that to your code you would need to remove the line:

Serial_ & dbgTerminal = Serial;

and change the line:

while (!dbgTerminal) { }

to

while (DEBUG && !Serial) { }

This adds no overhead, minimal extra lines of code and can be turned on or off just by changing the value of DEBUG. You can easily expand the system to add multiple levels of debug output, for example dbgTerminalCommand, dbgTerminalInfo, dbgTerminalError.

Please always use code tags(</> button on the toolbar) when you post code or error/warning messages. If you look at the code you posted you'll notice that the [ i ] near the end disappeared and the text switched to italics. This is because the forum software interpreted the [ i ] as markup for italics. This wouldn't have happened if you used code tags.

Thanks a lot for your help . I'll let you know as soon as I make the change. :slight_smile: