learningtech
learningtech

Reputation: 33715

hw_timer_t, timerAttachInterrupt, portENTER_CRITICAL etc... not defined for ESP8266

I have an ESP8266 NodeMCU 12E development board. I'm trying to implement an ISR that uses a hardware timer as described by this blog here. The blog post was originally meant for ESP32 and it provides this final demonstration code which I can not get to compile within Arduino IDE for ESP8266.

volatile int interruptCounter;
int totalInterruptCounter;

hw_timer_t * timer = NULL;
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;

void IRAM_ATTR onTimer() {
  portENTER_CRITICAL_ISR(&timerMux);
  interruptCounter++;
  portEXIT_CRITICAL_ISR(&timerMux);

}

void setup() {

  Serial.begin(115200);

  timer = timerBegin(0, 80, true);
  timerAttachInterrupt(timer, &onTimer, true);
  timerAlarmWrite(timer, 1000000, true);
  timerAlarmEnable(timer);

}

void loop() {

  if (interruptCounter > 0) {

    portENTER_CRITICAL(&timerMux);
    interruptCounter--;
    portEXIT_CRITICAL(&timerMux);

    totalInterruptCounter++;

    Serial.print("An interrupt as occurred. Total number: ");
    Serial.println(totalInterruptCounter);

  }
}

When I try to compile, I get the errors that say hw_timer_t, portENTER_CRITICAL, portEXIT_CRITICAL, timerAttachInterrupt, timerAlarmWrite, etc... all don't exist.

Am I supposed to import some library to support this demonstration code?

I can't seem to find talks of hardware timer for ESP8266. Every one seems to talk about hardware timer for ESP32 instead.

Upvotes: 3

Views: 3783

Answers (1)

romkey
romkey

Reputation: 7109

They're not defined because they're in the ESP32 SDK, which is completely separate (different CPU, different instruction set, different OS) from the ESP8266. Documentation about the ESP32 won't apply to the ESP8266.

Take a look at the ESP8266 "NONOS SDK" - this is the "OS" that the ESP8266 Arduino SDK is built on. It includes calls for hardware timers (hw_timer_init(), hw_timer_arm(), hw_timer_set_func()). You can find the documentation for it here.

Beware, there's also a "Free RTOS" for the ESP8266. When you're searching for example code, people are often not clear about whether their code is for the NONOS SDK or the Free RTOS SDK.

Free RTOS a separate piece of software; you won't be able to use its functions in an Arduino SDK program. Some people have gotten parts of the Arduino SDK running with it but that's a deep rabbit hole that can waste a lot of your time. If you decide to go that route you're better off abandoning the Arduino SDK calls and just writing a proper FreeRTOS program.

Upvotes: 1

Related Questions