将A或B线连接到INT0,利用外部中断0计数脉冲数,再利用定时器定时1秒后读取计数,并计算对应角度,最后由LCD显示所得转速
#include<reg52.h>
typedef unsigned int u16;
typedef unsigned char u8;
#define DATA P0
sbit rs = P3^5;
sbit rw = P3^6;
sbit en = P3^4;
sbit du = P2^6;
sbit we = P2^7;
sbit P1_0=P1^0;
u8 count;
u16 z,num,n;
void delay(u16 z)
{
u16 x,y;
for(x=z;x>0;x--)
for(y=114;y>0;y--);
}
void write_cmd(u8 cmd)
{
rs = 0;
rw = 0;
DATA = cmd;
delay(5);
en = 1;
delay(5);
en = 0;
}
void write_data(u8 dat)
{
rs = 1;
rw = 0;
DATA = dat;
delay(5);
en = 1;
delay(5);
en = 0;
}
void write_sfm(u8 add,u16 date)
{
u8 bai,shi,ge;
bai = (date%1000)/100;
shi = (date%100)/10;
ge = date%10;
write_cmd(0x80+add);
write_data(0x30+bai);
write_data(0x30+shi);
write_data(0x30+ge);
}
void lcd_init(void)
{
du = 0;
we = 0;
write_cmd(0x02);
write_cmd(0x06);
write_cmd(0x0c);
write_cmd(0x38);
write_cmd(0x01);
write_cmd(0x80+9);
write_data(0xdf);
EA = 1;
IT0 = 1;
EX0 = 1;
// PX0 = 1;
TMOD = 0x01;
TH0 = 0x4b;
TL0 = 0xfd;
ET0 = 1;
TR0 = 1;
}
int main(void)
{
rw = 0;
rs = 0;
en = 0;
lcd_init();
while(1)
{
P1_0=1;
}
}
void int0() interrupt 0
{
num++;
}
void timer0() interrupt 1
{
TH0=0x4b;
TL0=0xfd;
count++;
if(count==20) //定时1秒
{
P1_0 = 0;
n = num*0.18; //1秒所转的角度 这个编码器的分辨率为2000P/R
write_sfm(5,n);
delay(20);
num=0;
count = 0;
}
} |