赞
踩
mh sensor series模块有四个口,VCC接5V,GND接地,还有A0与D0分别是模拟量与数字量的输出。
和单片机使用,就只用D0口即可.
使用单片机的外部中断进行引脚检测。可以选择P3^2或者P3^3.
这里选择外部中断1,工作模式2
还需要使用定时器中断来检测时间差。
如果使用,可以直接复制代码,然后修改引脚即可。使用的共阳极两段数码管。
- /*
- * @Author:Booksort
- * @fuc: 多少圈/秒,去151修改
- *
- */
-
- #include <REG52.H>
- #include <stdio.h>
-
- #define uint8 unsigned char
- #define uint32 unsigned int
-
-
-
- uint8 code Num_CA[] = {0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8, 0x80, 0x90};
-
- unsigned char PWM_T=0;
-
-
- unsigned char PWML=30;//左轮占空比
- unsigned char PWMR=30;//有轮占空比
-
- unsigned char Run_Flag=0;//电机模式->0-停止;1-运行
-
-
- static char Key_Up=0;
-
-
- sbit sm1=P2^0;
- sbit sm2=P2^1;
- //使能1-左
- sbit ENL=P1^2;
- sbit INL1=P1^3;
- sbit INL2=P1^4;
-
-
- //使能2-右
- sbit ENR=P1^5;
- sbit INR1=P1^6;
- sbit INR2=P1^7;
-
- //拨码开关
- sbit DialSwitch1=P2^5;
- sbit DialSwitch2=P2^6;
-
- //外部中断 P3^2,P3^3
- sbit Deng=P1^0;
- sbit KEY=P3^3;
-
- char Speed=0;
-
- uint8 t1=0;
- uint8 t2=0;
- uint32 TIME=0;
- char Tspeed=0;
-
- void delay_ms(int xms);
- void Display_Num_Fuc1(uint8 num);
-
- void Forward(void);
- void BackForward(void);
- void Run(void);
-
- void main(void)
- {
-
- TMOD |=0x01;
- TL0 = (65536-1000)%256; //设置定时初始值
- TH0 = (65536-1000)/256; //设置定时初始值
- ET0=1;
- IT1=0;
- EX1=1;
- EA=1;
- TR0 = 1; //定时器0开始计时
- while(1)
- {
- Run();
- Forward();
- if(DialSwitch1==0&&DialSwitch2==0)
- {
- PWML=100;
- PWMR=100;
- }
- else if(DialSwitch1==0&&DialSwitch2==1)
- {
- PWML=50;
- PWMR=50;
- }
- else if(DialSwitch1==1&&DialSwitch2==0)
- {
- PWML=10;
- PWMR=10;
- }
- else
- {
- PWML=0;
- PWMR=0;
- }
-
- if(Speed>=0&&Speed<=99)
- Display_Num_Fuc1(Speed);//显示多少圈每秒
- }
- }
-
-
- //定时器0中断
- void Timer0() interrupt 1
- {
- TL0 = (65536-1000)%256; //设置定时初始值
- TH0 = (65536-1000)/256; //设置定时初始值
-
- TIME++;
- if(PWM_T>200)//周期>>1ms*200=200ms
- {
- PWM_T=0;
- }
- if(Run_Flag==1)
- {
- if(PWM_T<=PWML)
- {
- ENL=1;
- }
- else
- {
- ENL=0;
- }
- if(PWM_T<=PWMR)
- {
- ENR=1;
- }
- else
- {
- ENR=0;
- }
- }
- else if(Run_Flag==0)
- {
- ENL=ENR=0;
- }
-
- PWM_T++;
-
- if(KEY==1&&Key_Up==1)
- {
- Key_Up=0;
-
- Deng=1;
- Tspeed++;
- }
-
- if(TIME>=1000)
- {
- Speed=Tspeed;
- Tspeed=0;
- TIME=0;
-
- }
- }
-
-
- //60*1000
- void exint1() interrupt 2
- {
-
- if(Key_Up==0)
- {
- Key_Up=1;
- t1=t2;
-
- Deng=0;
- }
- }
-
- void delay_ms(int xms)
- {
- int x,y;
- for(x=xms;x>=0;x--)
- {
- for(y=100;y>=0;y--)
- {}
- }
- }
- void Display_Num_Fuc1(uint8 num)
- {
- //2位数码管,显示区间[0,99],超过区间最大值,就变成区间最小值
- //数码管的2个位选,实时切换
- //使用数组来维护各个数码管显示的数字
- P0=0xFF;
- //P2=0x02;
- sm1=0;
- sm2=1;
- P0=Num_CA[num%10];
- num=num/10;
- //delay_ms(1);
- P0=0xFF;
- //P2=0x01;
- sm1=1;
- sm2=0;
- P0=Num_CA[num];
- //delay_ms(1);
-
- }
-
-
- void Run(void)
- {
- Run_Flag=1;
- }
-
- void Forward(void)
- {
- INL1=1;
- INL2=0;
- INR1=1;
- INR2=0;
- }
-
- void BackForward(void)
- {
- INL1=0;
- INL2=1;
- INR1=0;
- INR2=1;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。