STC15F2K60S2单片机读取光栅尺距离

2019-04-15 17:44发布

/* 2脚 ------ GND 6脚 A -----P32 8脚 B -----P33 9脚 Z ----- 7脚 -------VCC //注意,烧录程序时,最好把晶振调整到17Mhz */ #include "stc15f2k60s2.h" #include "display.h" #include "intrins.h" sbit PIN_B = P3^3; long num_B,num_A; unsigned int volatile counter = 0; //编码器脉冲计数 float count = 0; void commont(void) { P2 = 0xa0; P0 = 0x10; P2 = 0x80; P0 = 0xff; } void display_mc(unsigned long x,unsigned long y) { num_A = x; display(0x01,(int)num_A/100/10%10); display(0x02,(int)num_A/100%10); display(0x04,(int)num_A/10%10); display(0x08,(int)num_A%10); num_B = y; display(0x10,(int)num_B/100/10%10); display(0X20,(int)num_B/100%10); display(0x40,(int)num_B/10%10); display(0x80,(int)num_B%10); } void main(void) { commont(); IT0=1; //等于0为电平触发方式,低电平有效,等于1为脉冲触发方式,下降沿有效。 EA=1; //外部总中断打开 EX0=1; //外部中断0打开 while(1) { count = counter/50; display_mc(count,0); } } void Int0(void) interrupt 0 { EX0=0; if(!PIN_B)counter++; //中断计数 -------正向移动时,A为下降沿是,B为高电平 if(PIN_B)counter--; //中断计数 -------反向移动时,A为下降沿是,B为低电平 EX0=1; } #ifndef __DISPLAY_H_ #define __DISPLAY_H_ #include"stc15f2k60s2.h" #include"intrins.h" unsigned char code tab[]={0XC0,0XF9,0XA4,0XB0,0X99,0X92,0X82,0XF8,0X80,0X90,0xff,0xBF}; void delay(unsigned char i) { unsigned char a,b; for(a=i;a>0;a--) for(b=110;b>0;b--); } void smg_duan(unsigned char duan) { P0=tab[duan]; P2|=0XE0; P2=0; } void smg_wei(unsigned char wei) { P0=wei; P2|=0xc0; P2&=0XDF; P2=0; } void display(unsigned char wei,unsigned char duan) { smg_wei(wei); smg_duan(duan); delay(10); smg_duan(10); smg_wei(0X00); } #endif