新手入门
- 积分
- 8
- 金钱
- 8
- 注册时间
- 2023-3-13
- 在线时间
- 1 小时
|
2金钱
lz写了一份能够计算产生特定频率pwm的代码,相对误差大约在1%以内。但是我并不清楚这个算法的数学依据是什么,希望各位能够帮忙解决一下。- struct {
- unsigned long int prescale;
- unsigned long int autoreload;
- unsigned long int err;
- }pwm, pwm_calc;
- void pwm_generate(unsigned long int freq)
- {
- memset(&pwm, 0x00, sizeof(pwm));
- memset(&pwm_calc, 0x00, sizeof(pwm_calc));
- pwm.err = pwm.err - 1;
- for (pwm_calc.prescale = 1; pwm_calc.prescale < 65535UL && pwm_calc.prescale; pwm_calc.prescale++) {
- pwm_calc.autoreload = (80000000UL / ((pwm_calc.prescale + 1) * freq)) - 1;
- if (pwm_calc.autoreload > 65535UL || pwm_calc.autoreload < 100)
- continue;
- if (pwm_calc.autoreload * pwm_calc.prescale > freq)
- pwm_calc.err = pwm_calc.autoreload * pwm_calc.prescale - freq;
- else
- pwm_calc.err = freq - pwm_calc.autoreload * pwm_calc.prescale;
- if (pwm_calc.err < pwm.err)
- memcpy(&pwm, &pwm_calc, sizeof(pwm));
- }
- return;
- }
复制代码 附件里为测试结果
|
-
测试结果
|