Class to access the CycleCount register to measure instructions executed.

I have to give the credit to the stmicro forums for how to enable the feature, but the class below counts program instruction ticks. I couldn’t find the registers already defined in the due headers, but it works perfectly, and should work the same on any Cortex-M3.

class CycleCount {
	volatile uint32_t *DWT_CYCCNT;
	volatile uint32_t *DWT_CONTROL;
	volatile uint32_t *SCB_DEMCR; // debug exception and monitor control

public:

	CycleCount() {
		DWT_CYCCNT = (volatile uint32_t *) 0xE0001004;
		DWT_CONTROL = (volatile uint32_t *) 0xE0001000;
		SCB_DEMCR = (volatile uint32_t *) 0xE000EDFC;
	}

	void init(void) {
		*SCB_DEMCR |= 0x01000000;
		*DWT_CYCCNT = 0; // reset the counter
		*DWT_CONTROL |= 1; // enable the counter
	}

	inline uint32_t ticks() {
		return *DWT_CYCCNT;
	}

	inline uint32_t micros() {
		static const uint16_t DIV = F_CPU / 1000 / 1000;
		return *DWT_CYCCNT / DIV; // TODO: will skip when wrapping, only use to check drift!
	}

	inline void reset() {
		*DWT_CYCCNT = 0;
	}
};