ESP8266-12 crash

Hello,

The buzz() function shown below works fine when executed on an Arduino but fails when it’s executed on an ESP8266-12. It causes a memory overflow and, therefore, a crush.

I cannot understand why. Can someone pls help me understand where the error is?

TIA

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager

byte buzzPin = 4; // pin 2 fails as well

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
  //reset saved settings
  //wifiManager.resetSettings();

  //set custom ip for portal
  //wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

  //fetches ssid and pass from eeprom and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  wifiManager.autoConnect("AutoConnectAP");
  //or use this for auto generated name ESP + ChipID
  //wifiManager.autoConnect();


  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");

  buzz(buzzPin, 2000, 2000);

}

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

}

void buzz(byte pin, uint16_t frequency, uint16_t duration)
{ // input parameters: Arduino pin number, frequency in Hz, duration in milliseconds
  unsigned long startTime = millis();
  unsigned long halfPeriod = 1000000L / frequency / 2;
  
  pinMode(buzzPin, OUTPUT);

  while (millis() - startTime < duration)
  {
    digitalWrite(buzzPin, HIGH);
    delayMicroseconds(halfPeriod);
    digitalWrite(buzzPin, LOW);
    delayMicroseconds(halfPeriod);
  }

  pinMode(buzzPin, INPUT);

}

What I don't understand is why your function changes the mode of the pin that the buzzer is attached to. You seem to think that maybe you'll read from the buzzer at some point.

You also seem to think that you can use any pin for any purpose, like on an Arduino. That is NOT the case on the ESP8266.

And, the device crashes, not crushes.

Thanks for the reply.

I know it’s an unusual code and that an easy fix would be as follows but I was just wondering why it crashes :slight_smile: on the ESP. It doesn't seem to be pin related so, I just wanted to satisfy my curiosity.

  tone(buzzPin, 880, 300);
  delay(300);
  tone(buzzPin, 523, 200);
  delay(200);

What value is actually computed for halfPeriod?

Add more Serial.print() statements to the code. Which line actually causes the crash?

Also, the ESP8266 is very sensitive to blocking code and resets via a watchdog timer if these block for too long.

See: for example