Simple generator for a range of predefined frequencies using the M2's PWM module

kranenborg

Senior Member
Dear forum members,

Often one needs a pre-defined range of frequencies to be generated, the values steered by a potentiometer or similar sensor.

The following simple code for a 08M2 provides for a range of frequencies (with fixed 50% duty cycle), using the M2's PWM module. In the attached program, a range of 10kHz - 60kHz is generated on the PWM-output of the 08M2 (C.2), based on the 8-bit ADC input at C.4.
Significantly lower frequencies can be generated by adding the PWMDIVxx keyword as the first parameter to the PWMOUT command in the program (or changing the M2's clock frequency). For example, using PWMDIV64 the range becomes 156Hz - 938Hz.
Higher frequencies are possible simply by increasing the clock frequency using SETFREQ m16 (20kHz - 120kHz) or even m32.

Since some expressions need to be evaluated given the M2's 16-bit arithmetic and ditto register size constraints, and the period parameter of the PWMOUT command has a byte size, the code is optimized to limit loss of information during mathematical operations, primarily multiplications and divisions. For example, the peculiar definitions of the min and max frequency range in the code facilitate maximal value range usage during expression evaluation in the registers (for example, generally one wants to do multiplications first up to values close to the 16-bit max value (65535) in a register before applying a division operator). The code is properly documented.

I hope this provides for a quick-and-dirty way to generate a large range of frequencies on M2-processors without any external hardware.
Regards, Jurjen
https://www.kranenborg.org/electronics

Edit: Attached file replaced due to small correction: period must be a byte variable
 

Attachments

Last edited:
Top