|
我的單片機(jī)和SG90 9g舵機(jī)是用的一個(gè)電源。信號(hào)線接在了P1^0上面。但是我用按鍵控制舵機(jī)方向的時(shí)候。遇到了以下問(wèn)題。困擾許久,還請(qǐng)51黑的大神不吝賜教。
我在程序里采用count來(lái)定時(shí)。每0.5ms進(jìn)入一次中斷。count == 40為一個(gè)周期20ms。用PWM_count 控制方向。初始值為1(轉(zhuǎn)向0度)。2(轉(zhuǎn)向45度)3轉(zhuǎn)向90度。分別用s2 s3 s4按鈕對(duì)其PWM_count進(jìn)行修改。但是我在使用中發(fā)現(xiàn)。我按下s4后舵機(jī)會(huì)正常的轉(zhuǎn)到90度,然后會(huì)自己又轉(zhuǎn)回到單片機(jī)初始值的設(shè)置值1也就是0度。按下s3也是轉(zhuǎn)45度又回到0度。通過(guò)調(diào)試發(fā)現(xiàn)是PWM_count的值自動(dòng)變?yōu)榱?造成的。這種情況是單片機(jī)復(fù)位造成的嗎?
一個(gè)星期了,還是沒(méi)有解決。下面是程序,大佬們幫看看。
- #include<reg52.h>
- sbit SG_PWM=P1^0;
- unsigned char count=0;
- unsigned char PWM_count=1; //初始值 1--0度,2--45度,3--90
- unsigned char a=0;
- sbit s2 = P3^0;
- sbit s3 = P3^1;
- sbit s4 = P3^2;
- sbit led1 = P1^2;
- sbit led2 = P1^3;
- void Timer_Init()
- {
- TMOD=0X01; //T0定時(shí)方式1
- TH0=0xfe;
- TL0=0x33; //計(jì)數(shù)初值設(shè)置為0.5ms
- ET0=1; //打開(kāi)定時(shí)器0的中斷
- TR0=1; //打開(kāi)定時(shí)器0
- EA=1; //開(kāi)總中斷
- }
- /**
- * 延時(shí)函數(shù)
- **/
- void delay(unsigned int i)
- {
- unsigned int x,y;
- for(x = i; x > 0; x--)
- for(y = 120; y > 0 ; y--);
- }
- void Timer() interrupt 1 //特別注意此處,0--外部中斷0,1--定時(shí)器中斷0,2--外部中斷1,3--定時(shí)器中斷1,4--串行口中斷1
- {
- TR0=0;
- TH0=0xfe;
- TL0=0x33; //重新賦計(jì)數(shù)初值為0.5ms
- if(count<=PWM_count)
- {
- SG_PWM=1;
- }
- else
- {
- SG_PWM=0;
- }
- count++;
- if(count>=40)
- {
- count=0;
- a++;
- }
- TR0=1;
- }
- void main()
- {
- Timer_Init();
- while(1){
- if(s2 == 0){
- delay(100);
- if(s2 == 0){
- count = 0;
- PWM_count = 1;
- }
- }
-
- if(s3 == 0){
- delay(100);
- if(s3 == 0){
- count = 0;
- PWM_count = 2;
- }
- }
-
- if(s4 == 0){
- delay(100);
- if(s4 == 0){
- count = 0;
- PWM_count = 3;
- }
- }
-
- if(PWM_count == 1){
- led1 = 0;
- led2 = 1;
- }
-
- if(PWM_count == 3){
- led1 = 1;
- led2 = 0;
- }
-
- }
- }
復(fù)制代碼
|
|