ESP 32 code not uploading

Whenever I try uploading my code I get this error message:
Sketch uses 315039 bytes (24%) of program storage space. Maximum is 1310720 bytes.
Global variables use 23800 bytes (7%) of dynamic memory, leaving 303880 bytes for local variables. Maximum is 327680 bytes.
esptool v5.1.0
Serial port COM5:
Connecting......................................
A fatal error occurred: Failed to connect to ESP32: Invalid head of packet (0x00): Possible serial noise or corruption.
For troubleshooting steps visit: Troubleshooting - ESP32 - — esptool latest documentation

Failed uploading: uploading error: exit status 2

And my serial monitor is a garbled mess

I've tried 3 sperate cables, only one was even recognized by my computer.
And I'm hoping my board isn't fried or something.

Also I'm using this specific Esp-32 Amazon.com: HiLetgo ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA for Arduino IDE : Electronics

Hi @smonshmonster.

This error might be caused by the communication lines between the computer and the microcontroller on the board not being able to support the rather high default upload speed. If so, the problem should be fixed by reducing the upload speed, which is configurable via a convenient menu.

Select Tools > Upload Speed > 115200 from the Arduino IDE menus and then try uploading the sketch again, just as you did before. Hopefully this time the upload will be successful. If not, add a reply here on this forum topic to let us know and we'll investigate further.

Optimizing Upload Speed

If the sketch upload no longer failed after reducing the upload speed, you will have determined that the board is not capable of managing uploads at the default 921600 baud, but is capable of them at 115200 baud.

Especially with more complex sketches, the upload will take a significant amount of time at 115200 baud. It is likely that the board is capable of managing uploads at some speed higher than 115200 baud, so it is worth doing some experimentation to determine the maximum speed at which you can reliably upload to the board. You can do this by repeating the "Configure Upload Speed" procedure above, but selecting different speeds each time. Then attempting an upload to see if the new speed is appropriate.

1 Like

Already tried that, just replaced the board, and cable. Now I got a new error message.


I've gotten this error before with the old setup, to solve it last time, I just retried, and retried again. And I got the old error message. That solution doesn't work anymore.

Also here's the code I'm trying to upload.

/* ============================================================
   Aliens-Style Pressure Tracker (UNO/Nano Port, 4 sensors)
   - AVR-friendly (low RAM), page-buffered OLED with U8g2
   - 50 Hz sampling, drift removal, 0.2–10 Hz band-limit
   - Common-mode cancel, simple event score, 2D direction
   Hardware:
     - Arduino UNO/Nano (ATmega328P)
     - TCA9548A I2C mux @ 0x70
     - 4x LPS22HB/LPS22DF sensor breakouts (channels 0..3)
     - SSD1306 128x64 I2C OLED @ 0x3C
   ============================================================ */

#include <Arduino.h>
#include <AceWire.h>
#include <TCA9548A.h>
#include <Adafruit_LPS2X.h>
#include <U8g2lib.h>

// -------- Display (U8g2 page buffer = AVR friendly) ----------
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, U8X8_PIN_NONE);

// -------- I2C Mux & Sensors ---------------------------------
TCA9548A tca;
Adafruit_LPS22 lps[4];  // 0:N, 1:E, 2:S, 3:W

// -------- Pins ----------------------------------------------
const int BUZZ_PIN = 7;       // set to -1 to disable buzzer

// -------- Sampling config -----------------------------------
const float FS = 50.0f;       // 50 Hz per sensor (good on AVR)
const float DT = 1.0f / FS;

// Simple 1st-order filters (lightweight math)
// High-pass ~0.2 Hz
const float HP_FC = 0.2f;
const float HP_ALPHA = (1.0f / (2.0f * 3.14159f * HP_FC)) / ((1.0f / (2.0f * 3.14159f * HP_FC)) + DT);

// Low-pass ~10 Hz
const float LP_FC = 10.0f;
const float LP_ALPHA = DT / ((1.0f / (2.0f * 3.14159f * LP_FC)) + DT);

// Slow EMA for drift removal (~5 s)
const float DC_ALPHA = DT / (5.0f + DT);

// Event detection
float noise_floor = 0.05f;
float thresh_mult = 4.0f;

// Per-channel filter state
struct ChanState {
  float dc;   // slow drift estimate
  float hp;   // high-pass state
  float lp;   // low-pass state
  float xprev;
};
ChanState st[4];

uint8_t chanIdx[4] = {0,1,2,3};  // TCA channels N,E,S,W

// Timing
unsigned long lastTick = 0;
const unsigned long TICK_US = (unsigned long)(DT * 1000000.0f);

void safeBeep(uint16_t ms=25) {
  if (BUZZ_PIN < 0) return;
  digitalWrite(BUZZ_PIN, HIGH);
  delay(ms);
  digitalWrite(BUZZ_PIN, LOW);
}

bool selectChannel(uint8_t ch) {
  tca.closeAll();
  tca.openChannel(ch);
  delayMicroseconds(150);
  return true;
}

bool readPressurePa(uint8_t i, float &p) {
  selectChannel(chanIdx[i]);
  sensors_event_t temp, pres;
  if (!lps[i].getEvent(&pres, &temp)) return false;
  p = pres.pressure * 100.0f;  // hPa -> Pa
  return true;
}

void drawRadar(float vx, float vy, float energy, bool ev) {
  u8g2.clearBuffer();

  // Simple HUD numbers
  u8g2.setFont(u8g2_font_5x8_tf);
  u8g2.setCursor(0, 8);
  u8g2.print(F("E:"));
  u8g2.print(energy, 2);
  u8g2.print(F(" NF:"));
  u8g2.print(noise_floor, 2);

  // Radar at bottom center
  const int cx = 64;
  const int cy = 63;
  const int r  = 26;

  // Ground line
  u8g2.drawHLine(0, cy, 128);
  // Circles
  u8g2.drawCircle(cx, cy, r, U8G2_DRAW_ALL);
  u8g2.drawCircle(cx, cy, r/2, U8G2_DRAW_ALL);

  // Scale vector to fit circle
  float mag = sqrt(vx*vx + vy*vy);
  float scale = (mag > 1e-6f) ? (r * 0.9f / mag) : 0.0f;
  int bx = cx + int(vx * scale);
  int by = cy - int(vy * scale);

  if (ev) {
    u8g2.drawDisc(bx, by, 3, U8G2_DRAW_ALL);
  } else {
    u8g2.drawCircle(bx, by, 2, U8G2_DRAW_ALL);
  }

  // NESW labels (assume +vy is "north" up)
  u8g2.setCursor(60, 12);
  u8g2.print(F("N"));
  u8g2.setCursor(118, 34);
  u8g2.print(F("E"));
  u8g2.setCursor(60, 63 - r - 2);
  // already have circle; optional label for clarity

  u8g2.sendBuffer();
}

void setup() 
{
  if (BUZZ_PIN >= 0) {
    pinMode(BUZZ_PIN, OUTPUT);
    digitalWrite(BUZZ_PIN, LOW);
  }

  Wire.begin();
  Wire.setClock(400000); // fast I2C helps

  u8g2.begin();
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_6x10_tf);
  u8g2.drawStr(0,12,"Pressure Tracker (AVR)");
  u8g2.sendBuffer();
  
/* Error, "no matching function for call to 'TCA9548A::begin(int)'"
 openChannel does not work either, "expected primary-expression  before numeric constant" WHAT IS THE PRIMARY EXPRESSION!?!? 
  if (!tca.openChannel(uint8_t 0x70 address)) {
    u8g2.clearBuffer();
    u8g2.drawStr(0,12,"TCA9548A not found!");
    u8g2.sendBuffer();
    while(1);
  }
*/
  // Init sensors
  for (uint8_t i=0;i<4;i++) {
    selectChannel(chanIdx[i]);
    if (!lps[i].begin_I2C()) {
      u8g2.clearBuffer();
      u8g2.drawStr(0,12,"LPS22 init fail ch:");
      u8g2.setCursor(110,12); u8g2.print(i);
      u8g2.sendBuffer();
      while(1);
    }
    // 50 Hz ODR is fine (some LPS variants: 25/50/75/100)
    lps[i].setDataRate(LPS22_RATE_50_HZ);
    st[i] = {0,0,0,0};
    delay(10);
  }

  delay(300);
  safeBeep(15);
  lastTick = micros();
}

void loop() {
  unsigned long now = micros();
  if ((now - lastTick) < TICK_US) return;
  lastTick += TICK_US; // keep steady cadence

  // 1) Read sensors
  float raw[4];
  for (uint8_t i=0;i<4;i++) {
    float p;
    if (readPressurePa(i, p)) raw[i] = p;
    else raw[i] = raw[i]; // noop on fail
  }

  // 2) Per-channel: drift removal -> HP -> LP
  float y[4];
  for (uint8_t i=0;i<4;i++) {
    float x = raw[i];

    // Slow DC removal (EMA)
    st[i].dc += DC_ALPHA * (x - st[i].dc);
    float x_dc = x - st[i].dc;

    // 1st-order high-pass (0.2 Hz)
    st[i].hp = HP_ALPHA * (st[i].hp + x_dc - st[i].xprev);
    st[i].xprev = x_dc;

    // 1st-order low-pass (10 Hz) on HP output
    st[i].lp += LP_ALPHA * (st[i].hp - st[i].lp);

    y[i] = st[i].lp;
  }

  // 3) Common-mode rejection
  float mean = 0;
  for (int i=0;i<4;i++) mean += y[i];
  mean *= 0.25f;
  for (int i=0;i<4;i++) y[i] -= mean;

  // 4) Energy (simple L2 norm)
  float energy = 0;
  for (int i=0;i<4;i++) energy += y[i]*y[i];
  energy = sqrt(energy);

  // Auto noise floor (slowly adapts)
  static float nfEMA = 0.05f;
  nfEMA += 0.01f * (energy - nfEMA);
  if (nfEMA < 0.02f) nfEMA = 0.02f;
  noise_floor = nfEMA;

  // 5) Direction vector (E-W, N-S)
  float vx = y[1] - y[3]; // +vx -> East
  float vy = y[0] - y[2]; // +vy -> North

  bool detected = (energy > (thresh_mult * noise_floor));

  // 6) Beep on rising edge
  static bool prev = false;
  if (detected && !prev) safeBeep(15);
  prev = detected;

  // 7) Draw
  drawRadar(vx, vy, energy, detected);
}

Also the serial monitor changed .

Just had a quick glance and I can’t see your.

Serial.begin(115200);

Also, are you sure you are using a data cable and not a power cable? They both look the same. I always use 9600 baud for the old ESP32s and 115200 for newer boards.

Another thing you can try is holding down the BOOT button on the board until you see ‘Connecting in the serial monitor. Open the Serial Monitor, if you see this then you have selected the wrong port, or it hasn’t been selected.

Play with the settings until that message disappears. One more thing to try is close the IDE and reopen it. you may have the port open on another Sketch.

Do I need that? If so where should I put it?
Also the uploading problem is solved! It was a wiring issue. New problem, the monitor is not working.

I never understand why people buy electronic components from Amazon. They only import them from China anyway, cut out the middleman and get them direct from AliExpress in China. You will pay up to a third of the price.

Try enabling this, upload again and let me know if it worked. Also add this to you setup

 Serial.begin(115200);

Amazon is way more expensive than people realize. But if they 'think' they are saving money with a 10% off sign in red
then they just go with it without thinking.
Swiping a card or hitting an 'order' button is less painful than spending cash.
Sorry this is a bit off topic.
Back on topic:
Buy a Freenove or a name brand Espressif board and well it just makes life easier, and they are built wayyy better with nice filtering capacitors and such, and multiple ground pins