Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save vvb333007/d3ef7e1fce628507ae2ceb92bd8aea0c to your computer and use it in GitHub Desktop.

Select an option

Save vvb333007/d3ef7e1fce628507ae2ceb92bd8aea0c to your computer and use it in GitHub Desktop.
32bit and 64bit microseconds counters on ESP32-S3. Undocumented.
// Example for ESP32-S3: two ways to read a microsecond timestamp.
//
// 1. Very fast, but returns only the lower 32 bits
// 2. Full 64-bit timestamp, slightly slower
//
// For simplicity, this example uses the Arduino framework.
//
// vvb333007@gmail.com
//
//
#include <Arduino.h>
#include <stdint.h>
// Timer command register
#define WIFI_TSF_CMD_REG (volatile uint32_t *)((uintptr_t)0x6003500c)
# define WIFI_TSFC_LATCH 1 // Latch current counter values into MMIO registers
// Latched 64-bit counter value
#define WIFI_TSF_HIGH_REG (volatile uint32_t *)((uintptr_t)0x6003501c)
#define WIFI_TSF_LOW_REG (volatile uint32_t *)((uintptr_t)0x60035018)
// Free-running 32-bit microsecond counter
#define WIFI_MICROS_REG (volatile uint32_t *)((uintptr_t)0x60035000)
// Fastest possible micros() implementation
//
uint32_t micros32() {
return *WIFI_MICROS_REG;
}
// Full 64-bit microsecond timestamp
// The logic is straightforward enough to not need much explanation
//
uint64_t micros64() {
uint32_t low, high;
// create snapshot
*WIFI_TSF_CMD_REG |= WIFI_TSFC_LATCH;
low = *WIFI_TSF_LOW_REG;
high = *WIFI_TSF_HIGH_REG;
*WIFI_TSF_CMD_REG &= ~WIFI_TSFC_LATCH;
// make 64bit result
return (((uint64_t)high) << 32) | (uint64_t)low;
}
void setup() {
Serial.begin(115200);
}
void loop() {
delay(1000);
Serial.printf("%llu , %lu\r\n", micros64(), micros32());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment