Teensy 4.x: Need help in understanding source code of analogWrite(pin, val)

Status
Not open for further replies.

sun0727

New member
Hello,

Now I'm learning how to control the PWM via Timer, so I viewed the source code for analogWrite().

For example, the following code is from pwm.c, which generates PWM signal by controlling the Quad Timer.

HTML:
void quadtimerWrite(IMXRT_TMR_t *p, unsigned int submodule, uint16_t val)
{
	uint32_t modulo = 65537 - p->CH[submodule].LOAD + p->CH[submodule].CMPLD1;
	uint32_t high = ((uint32_t)val * (modulo - 1)) >> analog_write_res;
	if (high >= modulo - 1) high = modulo - 2;

	//printf(" modulo=%lu\n", modulo);
	//printf(" high=%lu\n", high);
	uint32_t low = modulo - high; // low must 2 or higher
	//printf(" low=%lu\n", low);

	p->CH[submodule].LOAD = 65537 - low;
	p->CH[submodule].CMPLD1 = high;
}

What I know so far is:

LOAD: stores the value used to initialize the counter after counter compare.

CMPLD1: decides the cnt value used for comparison.


But what does modulo for? It looks like the number, which needs to be counted in one PWM period. But why does it have "strange" expressions (65535 + 2)? Why should low must 2 or higher?

Any help would be sincerely appreciated.
 
Status
Not open for further replies.
Back
Top