红外对管大多数的使用方法都是通过判断D0口的高低进行循迹,红外对管除了能用来循迹,还可以进行近距离的测距。测距范围在10cm左右。
如图,通过ADC检测A0口的电压进行测距,如果想要让这个值更稳定可以通过硬件或者软件滤波,硬件就是在A0和gnd之间加一个电容,软件滤波可以用算法,一下是我用的一个还可以的算法。
单片机源程序如下:
- #include "stc15.h"
- #include "intrins.h"
- #include "delayms.h"
- #include "ADC.h"
- #define N 12
- unsigned int value_buf[N];
- unsigned int temp=0;
- unsigned int dat_hight,dat_low;
- unsigned char i=0,j=0;
- extern unsigned char ch;
- int filter() //递推平均滤波法
- {
- unsigned char count;
- unsigned int sum=0;
- ADC_CONTR=ADC_POWER|ADC_START+ch;
- delayms(10);
- for(i=0;i<N;i++)
- {
- dat_hight=ADC_RES; //取ADC高八位
- dat_hight=dat_hight<<2; //将数据左移两位
- dat_low=ADC_RESL&0x03; //取ADC低两位
- value_buf[i]=dat_hight|dat_low;;
- ADC_CONTR=ADC_POWER|ADC_START+ch;
- delayms(10);
- }
- sum=0;
- for(i=0;i<N-1;i++)
- for(j=0;j<N-1-i;j++)
- {
- if(value_buf[j]<value_buf[j+1])
- {
- temp=value_buf[j];
- value_buf[j]=value_buf[j+1];
- value_buf[j+1]=temp;
- }
- }
- for(count=2;count<N-2;count++) sum+=value_buf[count];
- return (unsigned int)(sum/(N-4));
- }
复制代码
- #include "stc15.h"
- #include "ADC.h"
- #include "uart.h"
- #include "stdio.h"
- #include "delayms.h"
- #include "math_algorithm.h"
- #include "oled.h"
- sbit S2=P1^6;
- unsigned int number;
- void main()
- {
- delayms(10);
- ADC_init();
- uart_init(9600);
- OLED_Init();
- OLED_Clear();
- while(1)
- {
- while(S2==0)
- {
- delayms(10); //10ms消抖
- if(S2==0)
- {
- OLED_ShowNum(54,4,filter(),4,32);
- }
- while(!S2); //等待按键电平
- }
- }
- }
复制代码
所有资料51hei提供下载:
红外对管检测.zip
(70.32 KB, 下载次数: 68)
|