本文最后更新于:2022年5月29日 上午
定时器中断可以用于产生PWM信号,可以通过如下方式得到。
1、首先用之前不能忘了宏定义以下相应变量:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| sbit IN1=P1^2; sbit IN2=P1^3; sbit IN3=P1^6; sbit IN4=P1^7; sbit ENA=P1^4; sbit ENB=P1^5; unsigned char pwm_val_left =0; unsigned char pwm_val_right =0; unsigned char push_val_left =4; unsigned char push_val_right=4; sbit Right_PWM_ON=1; sbit Left_PWM_ON =1; unsigned int time=0;
|
2、产生PWM函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
void pwm_out_left_moto(void) { if(Left_PWM_ON) { if(pwm_val_left<=push_val_left) { ENA=1; } else { ENA=0; } if(pwm_val_left>=20) pwm_val_left=0; } else { ENA=0; } }
void pwm_out_right_moto(void) { if(Right_PWM_ON) { if(pwm_val_right<=push_val_right) { ENB=1; } else { ENB=0; } if(pwm_val_right>=20) pwm_val_right=0; } else { ENB=0; } }
void timer0()interrupt 1 using 2 { TH0=0XFC; TL0=0X66; pwm_val_left++; pwm_val_right++; pwm_out_left_moto(); pwm_out_right_moto(); }
|