最近学习了AD 觉得光敏检测很有意思
于是就根据光敏检测的值点个灯吧
使用的普中51 A2开发板
原理图在附件
源代码 如下
- #include <reg52.h>
- #define XPT2046_VBAT 0xAC
- unsigned int ADvalue;
- unsigned int led_num=0;
- sbit XPT2046_CS=P3^5;
- sbit XPT2046_DCLK=P3^6;
- sbit XPT2046_DIN=P3^4;
- sbit XPT2046_DOUT=P3^7;
- void Delay(unsigned int xms)
- {
- unsigned char i, j;
- while(xms--)
- {
- i = 2;
- j = 239;
- do
- {
- while (--j);
- } while (--i);
- }
- }
- unsigned int XPT2046_ReadAD(unsigned char Command)
- {
- unsigned int ADValue=0;
- unsigned char i;
- XPT2046_DCLK=0;
- XPT2046_CS=0;
-
- for(i=0;i<8;i++)
- {
- XPT2046_DIN=Command&(0x80>>i);
- XPT2046_DCLK=1;
- XPT2046_DCLK=0;
- }
-
- for(i=0;i<16;i++)
- {
- XPT2046_DCLK=1;
- XPT2046_DCLK=0;
- if(XPT2046_DOUT)
- {
- ADValue|=(0x8000>>i);
- }
- }
- XPT2046_CS=1;
- return ADValue>>8;
- }
- void led_light()
- {
- switch(led_num)
- {
- case 1:P2=0xfe;break;
- case 2:P2=0xfc;break;
- case 3:P2=0xf8;break;
- case 4:P2=0xf0;break;
- case 5:P2=0xe0;break;
- case 6:P2=0xc0;break;
- case 7:P2=0x80;break;
- case 8:P2=0x00;break;
- }
- }
- void pd()
- {
- if(ADvalue>0&&ADvalue<=10)
- led_num=1;
- else if(ADvalue>10&&ADvalue<=18)
- led_num=2;
- else if(ADvalue>18&&ADvalue<=26)
- led_num=3;
- else if(ADvalue>26&&ADvalue<=34)
- led_num=4;
- else if(ADvalue>34&&ADvalue<=42)
- led_num=5;
- else if(ADvalue>42&&ADvalue<=50)
- led_num=6;
- else if(ADvalue>50&&ADvalue<=52)
- led_num=7;
- else if(ADvalue>52)
- led_num=8;
- }
- void main()
- {
- while(1)
- {
- ADvalue=XPT2046_ReadAD(XPT2046_VBAT);
- Delay(5);
- pd();
- led_light();
- }
- }
复制代码
Keil代码工程51hei附件下载:
光强灯.zip
(20.84 KB, 下载次数: 27)
|