Search code examples
esp8266ticker

How to implement ticker callback at 100 micro seconds for ESP8266?


I have an ESP8266 NodeMCU 12E development board and I'm using the Arduino IDE. I'm trying to use a Ticker.h to sample an analog input consistently at a frequency of 10khz, which is one sample every 100us. I noticed that Ticker sampler; sampler.attach(0.0001,callbackfunc); didn't work because attach() won't take the value 0.0001.

So then I wrote the following code based on some guides that I saw:

#include <ESP8266WiFi.h>
#include <Ticker.h>

bool s = true;
void getSample()
{
  s = !s;
}
Ticker tickerObject(getSample, 100, 0, MICROS_MICROS);

const char *ssid =  "___";  // Change it
const char *pass =  "___";  // Change it

void setup()
{
  Serial.begin(115200);
  Serial.println(0);      //start
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, pass);

  tickerObject.start();

}


void loop()
{
    if(s == true)
    {
      Serial.println("True");
    }
    else
    {
      Serial.println("False");
    }
}

However, this did not compile because tickerObject.start() method did not exist. So what I did next was:

  1. Download the latest ticker package as a zip file
  2. Unzip the package from point 1
  3. Made a back up of C:\Users\john\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.0-beta2\libraries\Ticker
  4. Replaced the folder mentioned in point 3 with the Ticker folder in point 2.
  5. Restarted my Arduino IDE
  6. Compiled and ran the code
  7. Opened up the Serial Monitor

However, when I inspect the serial monitor, all it prints is "True". I was expecting the value s to toggle between true and false at a 10khz frequency.

What did I do wrong?


Solution

  • From the documentation of this library:

    The library use no interupts of the hardware timers and works with the micros() / millis() function.

    This library implements timers in software by polling the micros() and millis() functions. It requires the update() method to be called in loop().

    So the start of loop() should be:

    void loop()
    {
        tickerObject.update();
    
        if(s == true)
    

    I'm trying to use a Ticker.h to sample an analog input consistently at a frequency of 10khz

    It is worth a go but this is a software based solution that is prone to jitter depending on how often the event loop can be called.