/***实验现象:下载程序后四位数码管显示XPT2046芯片转换电位器模拟值,范围是0-4096,一般达不到最大4096,这个受你供电电压的影响。还有就是数码管个位出现数字跳动,是源于程序中编写了每50下读取XPT2046芯片转换电位器模拟值,一是避免XPT2046芯片转换电位器模拟量为数字跳动太快,二是体现了XPT2046芯片在进行转换电位器模拟值。***/ #include <reg52.h> #include<intrins.h> #define uint unsigned int #define uchar unsigned char #define GPIO_DUAN P3 uchar table[]={0x3f, 0x06, 0x5b, 0x4f,0x66, 0x6d, 0x7d, 0x07,0x7f, 0x6f, 0x77, 0x7c,0x39, 0x5e, 0x79, 0x71}; uchar DisplayData[5]; sbit HCA = P2^2;//HCA,HCB,HCC是利用了74HC138译码器来进行位选,我们动态位选了4位 sbit HCB = P2^3; sbit HCC = P2^4; sbit CLK = P1^0; sbit CS = P1^1; sbit DIN = P1^2; sbit DOUT = P1^3; void DisplayDS(); void delayms(uint xms); uint Read_AD_Data(uchar moshi); void SPI_Write(uchar moshi); uint GetValue(); void main() { uint temp, cnt = 50; while(1) { if(cnt == 50)//每50下读取转换值,避免数字跳动太快 { temp = Read_AD_Data(0x94); cnt = 0; } cnt++; DisplayData[0] = table[temp/1000]; DisplayData[1] = table[temp%1000/100]; DisplayData[2] = table[temp%100/10]; DisplayData[3] = table[temp%10]; DisplayDS(); } } void DisplayDS()//动态扫描函数 { uint i; for(i = 0; i < 4; i++) { GPIO_DUAN = 0x00; switch(i) { case 0 : HCC = 0; HCB = 0; HCA = 0; break; case 1 : HCC = 0; HCB = 0; HCA = 1; break; case 2 : HCC = 0; HCB = 1; HCA = 0; break; case 3 : HCC = 0; HCB = 1; HCA = 1; break; } GPIO_DUAN = DisplayData[i]; delayms(1); } } void delayms(uint xms) { uint i, j; for(i = 0; i < xms; i++) for(j = 0; j < 110; j++); } uint Read_AD_Data(uchar moshi)//读取最终的数字量函数 { uint i, ans; SPI_Write(moshi); for(i = 0; i < 5; i++); CLK = 1; _nop_(); _nop_(); CLK = 0; _nop_(); _nop_(); ans = GetValue(); CS = 1; return ans; } void SPI_Write(uchar moshi)//写模式函数 { uint i; CS = 0; for(i = 0; i < 8; i++) { CLK = 0; DIN = moshi>>7; CLK = 1; moshi <<= 1; } CLK = 0; } uint GetValue()//读取DOUT管脚,得到最终数字量函数。 { uint i, ans = 0; for(i = 0; i < 12; i++) { CLK = 0; ans <<= 1; ans |= DOUT; CLK = 1; } CLK = 0; return ans; }