ESP32 Serial.print unstable

hi guys,
i am trying to sort out an issue and couldn´t find a clue yet, so decided to ask for help!
i have a code that was writen to arduino nano and i works very well, but i decided to move it to ESP32 for wifi comunication, so i reused the entire code and just changed ports definitions and included the littleFS and wifi libs.
The strange thing is that Serial monitor is not working properly, although the code still runs on the background (i have some leds attached to the board to confirm).
The issue is that during a "serial.print", it stops writing on the monitor and never comes back again.
i tried to migrate to VScode only to see if it was an issue on the IDE but it has the same issue.
on VScode i get a "␀" as a last character of the print.
I am having a hard time to find out what is going on, and i will try to sumarize some things i have already tested:

  • Change baud rate (lower and higher)
  • Change IDE to VScode
  • Change USB ports and cables
  • Change the computer used to monitor and upload the code
  • Change to Serial.print, printf, println, write.
  • Remove all libs that were included afterwards
  • Remove all special characters it could have.

The only difference i couldn´t test effect is that arduino uses CH340 and ESP uses CP2102.

Can anyone suggest any extra test to solve this mistery?
Thanks in advance!

I have the same code (GPS + SD card + 4-digit display + luxmeter), which I originally wrote for UNO/Nano, running on RP2040 (Pi Pico), ESP8266 (NodeMCU and D1 mini) and ESP32 (NodeMCU).
As you have done, I only reassigned the correct pins for each board and, except for some problematic library (Sd_Fat), I have not had any other problem, less than less with Serial.
Why don't you upload your code for review so we don't have to make any assumptions?

which ESP32 ports did you use? have a look at esp32-pinout-reference-gpios
you say you just used the Nano worrking code and changed ports and added the littleFS and wifi libs.- did it work before you added the littleFS and wifi libs?

Hi, i didn´t upload the code before because i believe it is quite long and may mislead the conversation... i will put here the code utin the end of void setup, that is where the issue is happening.

// v00.1 substituidos todos analogwrite por ledcAttachPin ,ledcWrite
// PLACA V00 PRECISA CONECTAR O SCL NO LUGAR DO PUL-
#include <Arduino.h>
#include <stdio.h>
// #define USE_LittleFS
#include "esp_ota_ops.h" 
//http://www.lucadentella.it/en/2018/10/27/esp32-37-ota-via-https/
// https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/esp_https_ota.html
#include "FS.h"
#include <LittleFS.h>//https://www.dobitaobyte.com.br/como-escrever-arquivos-no-spiffs-com-esp32/
#define TWOPART
#define FORMAT_LITTLEFS_IF_FAILED true
#include <WiFi.h>
#include <WebServer.h>
#include <WiFiManager.h>

// #include <WifiManager.h>
#include <Update.h>
#include <WiFiClient.h>
#include <HTTPClient.h>
#include <DNSServer.h>

//-------declaração de portas----------//
#define ledverdepin 27    // pino LEDVD
#define ledamarelopin 26  // pino LEDAM
#define ledvermelhopin 25 // pino LEDVM
#define ledbrancopin 33   // pino LEDBR
#define PULroletes 22     // pino SERVOPUL
#define DIRroletes 13     // pino SERVODIR
// #define pwmdescepin 32 // pino PONTEHDIR
// #define pwmsobepin 23 // pino PONTEHESQ
#define pwmdescepin 1            // canal PWM0
#define pwmsobepin 0             // canal PWM1
#define sverticaluppin 4         // pino PNP01
#define sverticaldownpin 16      // pino PNP02
#define Sinalparacanlockerpin 17 // pino PNP03
#define sgavetaabertapin 14      // pino PNP05
#define FDCroletespin 15         // pino PNP06
#define bautopin 39              // pino B01
#define bacionamentopin 34       // pino B02
#define bemergenciapin 35        // pino B03
#define Sinaldocanlockerpin 18   // pino R1
#define rmotoracpin 19           // pino R2
#define acsanalogpin 36          // pino AN01

//-------declaração de variaveis----------//

const long interval_Report = 18000;
unsigned long previousMillis_Report = 0;
unsigned long currentMillis_Report = 0;
boolean debug_mode = false;
boolean update_mode = false;
int Status_Debug;

// declarando variaveis de estado das IOs
unsigned int r1eststate = LOW;
unsigned int r2eststate = LOW;
unsigned int sverticalupstate = 1;
unsigned int sverticaldownstate = 1;
unsigned int bautostate = 1;
unsigned int sgavetaabertastate = 1;
unsigned int bacionamentostate = 1;
unsigned int bemergenciastate = 0;
unsigned int FDCroletesstate = 0;
unsigned int sroletestate = 1;
unsigned int Sinaldocanlockerstate = LOW;
unsigned int Sinalparacanlockerstate = HIGH;
unsigned int acsanalogstate;
// declarando variaveis genericas
unsigned int contador = 0;
unsigned int tipoemergencia = 0;
unsigned int FDCCORRENTESOBE = 600;
// função para ler valores da eeprom caso nao seja a primeira vez
unsigned int flag = 0;
// declarando variaveis para gravacao de numero de ciclos
unsigned int gravador = 0;
unsigned int ciclos = 0;
unsigned int enderecoCiclo = 0;
unsigned int enderecoCicloMULTIPLICADOR = 1;
unsigned int enderecoFDCsobe = 2;
// unsigned int enderecoACS = 4;
// unsigned int enderecoFDC2est = 4;
unsigned int ciclosInicial;
unsigned int ciclosMULTIPLICADORInicial;
unsigned int enderecovirgem = 5;
unsigned int enderecoCentralizar = 3;
unsigned int contadornaoacs = 0;
unsigned int state = HIGH;
unsigned int velocidadevertical = 120; // era 150
unsigned int velocidadedescida = 255;
// leituras dos valores caso nao seja o primeiro ciclo
unsigned int passos = 0;
unsigned int velocidade = 0;
boolean pulso;
unsigned int i = 0;
unsigned int passoscentralizar; // estimativa de passos para centralizar
unsigned int calib = 0;
int passos1estagio = 90; // v2.9 era 65, 24 dentes. agora 90 para 20 dentes//numero de passos realizados antes de ler o sensor fim de curso
int velocidade1estagio = 1700;
int passos2estagio = 90;
int velocidade2estagio = 1700;
int multmicropassos = 4; //(4 é para 800) passos multiplicador de passos, caso utilize a opção de micropassos do driver
int velocidadeconfig = 3000;
String SN = "0";
String num_ciclos;
int num_ciclos_int = 0;
String valortemp = "0";

void writeFile(fs::FS &fs, const char *path, String message)
{
  // void writeFile(fs::FS &fs, String path, String message){
  Serial.printf("Writing file: %s\r\n", path);
  File file = fs.open(path, "w");
  if (!file)
  {
    Serial.println("- failed to open file for writing");
    return;
  }
  if (file.print(message))
  {
    Serial.print(message);
    Serial.println(" - file written");
  }
  else
  {
    Serial.println("- write failed");
  }
  file.close();
}

/// String readFile(fs::FS &fs, String path){
String readFile(fs::FS &fs, const char *path)
{
  String content;
  Serial.printf("Reading file: %s\r\n", path);
  File file = fs.open(path);
  if (!file || file.isDirectory())
  {
    Serial.println("- failed to open file for reading");
  }
  while (file.available())
  {
    content = file.readString();
  }
  Serial.println("valor: " + content);
  file.close();
  return content;
}

void parametrosmemoria()
{
  //função criada para gerar documentos iniciais na gravação do equipamento
  if (!LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED))
  {
    Serial.println("LittleFS Mount Failed");
    return;
  }
  ///////valor do contador//////////se nao havia arquivo criado, ele cria e atribui valor 0, se havia, pega valor
  File file = LittleFS.open("/contador.txt", "r");
  if (!file || file.isDirectory())
  {
    //Serial.println("nao encontrou, criando");
    num_ciclos_int = 0;
    num_ciclos = String(num_ciclos_int);
    writeFile(LittleFS, "/contador.txt", num_ciclos);
    
  }
  else
  {
    num_ciclos = readFile(LittleFS, "/contador.txt");
    num_ciclos_int = num_ciclos.toInt();
  }
  Serial.println("ciclos: " + num_ciclos_int);

  ///////valor do serial//////////se nao havia arquivo criado, ele cria e atribui valor 0, se havia, pega valor
  file = LittleFS.open("/serial.txt", "r");
  if (!file || file.isDirectory())
  {
    //Serial.println("nao encontrou serial, criando");
    SN = "IL-003-0060";
    writeFile(LittleFS, "/serial.txt", SN);
  }
  else
  {
    SN = readFile(LittleFS, "/serial.txt");
  }
  Serial.print("novo Serial Number: " + SN);

  ///////valor do FDC sobe//////////se nao havia arquivo criado, ele cria e atribui valor 600, se havia, pega valor
  file = LittleFS.open("/FDCSOBE.txt", "r");
  if (!file || file.isDirectory())
  {
    //Serial.println("nao encontrou serial, criando");
    FDCCORRENTESOBE = 600;
    writeFile(LittleFS, "/FDCSOBE.txt", String(FDCCORRENTESOBE));
  }
  else
  {
    FDCCORRENTESOBE = readFile(LittleFS, "/FDCSOBE.txt").toInt();
  }
  Serial.print("FDC Sobe: " + FDCCORRENTESOBE);
  ///////valor do centralizacao//////////se nao havia arquivo criado, ele cria e atribui valor 60, se havia, pega valor
  file = LittleFS.open("/FDCSOBE.txt", "r");
  if (!file || file.isDirectory())
  {
    //Serial.println("nao encontrou serial, criando");
    passoscentralizar = 60;
    writeFile(LittleFS, "/passoscentralizar.txt", String(passoscentralizar));
  }
  else
  {
    passoscentralizar = readFile(LittleFS, "/FDCSOBE.txt").toInt();
  }
  Serial.print("passos centralizar: " + passoscentralizar);

}
void setup()
{
  LittleFS.begin();
  WebServer server(80);
  // GetInfo();
  Serial.begin(9600);
  // connectRede();
  Serial.println("V3.4 integ V00.2");
  parametrosmemoria(); //grava e resgata variaveis da memoria
  // configure LED PWM functionalitites
  // ledcSetup(ledChannel, freq, resolution);
  //  attach the channel to the GPIO to be controlled
  // ledcAttachPin(ledPin, ledChannel);
  ledcSetup(0, 25000, 8);
  ledcSetup(1, 25000, 8);
  ledcAttachPin(23, 0);
  ledcAttachPin(32, 1);

  //if (debug_mode==true)
  // {
  //  mododebug();
  // }
  //update_mode = digitalRead(bacionamentopin);
  //if (update_mode == LOW)
  // {
  //  modoupdate();
  // }

  Serial.print("FDC sobe: ");
  Serial.println(FDCCORRENTESOBE);
  // ciclos=ciclosInicial*10+(250*ciclosMULTIPLICADORInicial);
  Serial.print("Ciclos: ");
  Serial.println(ciclos);

  pinMode(rmotoracpin, OUTPUT);
  // pinMode(pwm1estpin, OUTPUT);
  // pinMode(pwm2estpin, OUTPUT);
  pinMode(PULroletes, OUTPUT);
  pinMode(DIRroletes, OUTPUT);
  pinMode(pwmsobepin, OUTPUT);
  pinMode(pwmdescepin, OUTPUT);
  pinMode(Sinaldocanlockerpin, OUTPUT);
  pinMode(Sinalparacanlockerpin, INPUT);
  pinMode(sverticaluppin, INPUT);
  pinMode(sverticaldownpin, INPUT);
  pinMode(bautopin, INPUT_PULLUP);
  pinMode(sgavetaabertapin, INPUT_PULLUP);
  pinMode(bacionamentopin, INPUT_PULLUP); //*****
  pinMode(ledbrancopin, OUTPUT);
  pinMode(ledamarelopin, OUTPUT);
  pinMode(ledverdepin, OUTPUT);
  pinMode(ledvermelhopin, OUTPUT);
  pinMode(bemergenciapin, INPUT_PULLUP);
  pinMode(FDCroletespin, INPUT_PULLUP);
  pinMode(acsanalogpin, INPUT);

  digitalWrite(Sinaldocanlockerpin, LOW);
  int tempoled = 70;
  digitalWrite(ledverdepin, HIGH); // liga  leds
  delay(tempoled);
  digitalWrite(ledamarelopin, HIGH); // liga leds
  delay(tempoled);
  digitalWrite(ledvermelhopin, HIGH); // liga leds
  delay(tempoled);
  digitalWrite(ledverdepin, LOW); // liga leds
  delay(tempoled);
  digitalWrite(ledamarelopin, LOW); // liga leds
  delay(tempoled);
  digitalWrite(ledvermelhopin, LOW); // liga leds
  delay(tempoled);
  digitalWrite(ledverdepin, HIGH); // liga  leds
  delay(tempoled);
  digitalWrite(ledamarelopin, HIGH); // liga leds
  delay(tempoled);
  digitalWrite(ledvermelhopin, HIGH); // liga leds
  delay(tempoled);
  digitalWrite(ledverdepin, LOW); // liga leds
  delay(tempoled);
  digitalWrite(ledamarelopin, LOW); // liga leds
  delay(tempoled);
  digitalWrite(ledvermelhopin, LOW); // liga leds
  ledcWrite(pwmsobepin, 0);  // PWM vertical desligado
  ledcWrite(pwmdescepin, 0); // PWM vertical desligado
  digitalWrite(PULroletes, LOW);
  digitalWrite(DIRroletes, LOW);
  primeirocheck();
  Serial.println("Pronto para operar!");
}

void loop()
{
  // put your main code here, to run repeatedly:

  // codigo para enviar report a cada 3 minutos se ocioso//

  int delay_entre_ciclos = 200; // quando entra no pelo modo auto, espera x tempo para iniciar o ciclo para nao cair a lata

  while (1)
  {
    unsigned long currentMillis_Report = millis();
    if (currentMillis_Report - previousMillis_Report >= interval_Report)
    {
      previousMillis_Report = currentMillis_Report;
      SetData("CONTADOR", String() + contador);
      // String IP=WiFi.localIP();
      // SetData ("IP",WiFi.localIP());
    }
    checkentradas();
    //    Serial.println("No loop");
    // se tiver com o emergencia em posição, sensor down em posição e a gaveta aberta, liga o led amarelo
    // if ((bemergenciastate == 0)&& (sverticaldownstate ==0)) //retirado gaveta
    // {//se tiver tudo certo menos a gaveta, liga o led amarelo
    //  digitalWrite(ledamarelopin, LOW);
    // }
    // else
    // {
    //    digitalWrite(ledamarelopin, HIGH);
    // }
    // check se devemos iniciar o ciclo

    if ((bautostate == 0) && (bemergenciastate == 0) && (sverticaldownstate == 0))
    {
      digitalWrite(Sinaldocanlockerpin, HIGH);
      // Serial.println("canlocker pronto, sinal para atuador enviado");
    }
    else
    {
      digitalWrite(Sinaldocanlockerpin, LOW);
    }
    Sinalparacanlockerstate = digitalRead(Sinalparacanlockerpin);
    if (Sinalparacanlockerstate == LOW)
    {
      Serial.println("sinal do atuador recebido para iniciar ciclo");
    }
    else
    {
      Serial.println("sinal do atuador nao recebido");
    }

    if ((((bautostate == 0) && (Sinalparacanlockerstate == LOW)) || (bacionamentostate == 0)) && (bemergenciastate == 0) && (sverticaldownstate == 0))
    { // se o sinal do atuador for LOW e estiver no auto, inicia o ciclo
      Serial.println("entrou no laço do ciclo");
      if (bautostate == 0)
      {
        contador = 0;
        //     Serial.println("entrou no auto");
        while (contador <= delay_entre_ciclos)
        {
          checkemergencia();
          delay(10); // se for o automatico, dá tempo entre ciclos
          contador = contador + 10;
          checkentradas();
          digitalWrite(ledamarelopin, LOW);
        }
      }
      ciclo();
      // ciclo concluido
      gravador = gravador + 1;
      if (gravador == 10) // a cada 10 ciclos armazena o numero de ciclos realizados
      {
        gravador = 0;
        ciclosInicial = ciclosInicial + 1;
        if (ciclosInicial == 251) // a cada 50 sobe o multiplicador
        {
          ciclosInicial = 0;
          ciclosMULTIPLICADORInicial = ciclosMULTIPLICADORInicial + 1;
          //          EEPROM.write(enderecoCicloMULTIPLICADOR, ciclosMULTIPLICADORInicial);
        }
        //        EEPROM.write(enderecoCiclo, ciclosInicial);
      }
      ciclos = ciclosInicial * 10 + (50 * ciclosMULTIPLICADORInicial) + gravador;
      Serial.print("Ciclos: ");
      Serial.println(ciclos);
    }
    // printbotoes();
    checkemergencia();
    delay(10);
  }
}

does the serial output always stop at the same point?
can you identify the point in your code and add extra print statements?
what happens if you increase the baudrate to 115200?

so, my baud rate was set 115200 before, change to 9600 was already a try to find the issue, there is no effect.
it does not freeze always on the same print, i couldn´t really identify the trigger.
whay i noticed is that it always freeze inside a serial.print of a regular text under " ", not during printing of variables.(what is even more strange to me, but can be just a coincidence).
I have changed some prints back and forth and the result is the same: it does not freeze always on the same print.
i have even put a loop to repeat the same print, including digitalWrites high and low just to simulate a code, and it happens to freeze on the 30th time it is repeating...
my only guess right now is that it may be some issue with the serial COM driver but i have no clue how to test it.

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