#include // 修改該文件以適應(yīng)硬件環(huán)境/單片機(jī)型號(hào)等 // CH452常量定義 #include #define uchar unsigned char #define ushort unsigned short #define CH452_I2C_ADDR0 0x40 // CH452的ADDR=0時(shí)的地址 #define CH452_I2C_ADDR1 0x60 // CH452的ADDR=1時(shí)的地址,默認(rèn)值 #define CH452_I2C_MASK 0x3E // CH452的2線接口高字節(jié)命令掩碼 uchar KeyValue; sbit CH452_SDA=P1^7; sbit CH452_SCL=P1^6; sbit CH452_INT=P3^2; const uchar KeyCode[16]={0x40,0x41,0x42,0x43,//0,1,2,3 0x48,0x49,0x4A,0x4B,//4,5,6,7 0x50,0x51,0x52,0x53,//8,9,A,B 0x58,0x59,0x5A,0x5B};//C,D,E,F void CH452_I2c_Start() // 操作起始,兩線制方式,SDA用做中斷輸出,使用以下兩個(gè)函數(shù) {
// EX0=0; //禁止鍵盤中斷,防止開(kāi)始時(shí)被CH452中斷而進(jìn)入中斷服務(wù)程序中的START CH452_SDA=1; /*發(fā)送起始條件的數(shù)據(jù)信號(hào)*/ CH452_SCL=1; _nop_(); CH452_SDA=0; /*發(fā)送起始信號(hào)*/ _nop_(); CH452_SCL=0; /*鉗住I2C總線,準(zhǔn)備發(fā)送或接收數(shù)據(jù) */ _nop_(); }
void CH452_I2c_Stop() // 操作結(jié)束 { CH452_SDA=0; _nop_(); CH452_SCL=1; _nop_(); CH452_SDA=1; /*發(fā)送I2C總線結(jié)束信號(hào)*/ _nop_(); _nop_(); IE0=0; // 清除中斷標(biāo)志,因?yàn)橥ㄟ^(guò)SDA輸出數(shù)據(jù)所以會(huì)誤中斷 EX0=0; }
void CH452_I2c_WrByte(uchar dat) //寫一個(gè)字節(jié)數(shù)據(jù) { unsigned char i; for(i=0;i!=8;i++) // 輸出8位數(shù)據(jù) { if(dat&0x80) {CH452_SDA=1;} else {CH452_SDA=0;} _nop_(); CH452_SCL=1; dat<<=1; _nop_(); _nop_(); CH452_SCL=0; _nop_(); } CH452_SDA=1; _nop_(); CH452_SCL=1; // 接收應(yīng)答 _nop_(); _nop_(); CH452_SCL=0; _nop_(); }
unsigned char CH452_I2c_RdByte() //讀一個(gè)字節(jié)數(shù)據(jù) { unsigned char dat,i; CH452_SDA=1; dat=0; for(i=0;i!=8;i++) // 輸入8位數(shù)據(jù) { CH452_SCL=1; _nop_(); _nop_(); dat<<=1; if(CH452_SDA) dat++; // 輸入1位 CH452_SCL=0; _nop_(); } CH452_SDA=1; _nop_(); CH452_SCL=1; // 發(fā)出無(wú)效應(yīng)答 _nop_(); _nop_(); CH452_SCL=0; _nop_(); return(dat);
} //CH452寫命令函數(shù) void CH452_WriteCommand(unsigned int Command) { CH452_I2c_Start(); CH452_I2c_WrByte(((Command>>7)&0x3E)|0x40); CH452_I2c_WrByte(Command); CH452_I2c_Stop(); }
unsigned char CH452_Read() //讀取按鍵 { ushort cmd; uchar keycode; CH452_I2c_Start(); /*啟動(dòng)總線*/ CH452_I2c_WrByte((uchar)(cmd>>7)&CH452_I2C_MASK|0x01|CH452_I2C_ADDR1); keycode=CH452_I2c_RdByte(); /*讀取數(shù)據(jù)*/ CH452_I2c_Stop(); /*結(jié)束總線*/ return(keycode); }
void CH452_Init() { uchar KeyValue; IT0=0; //設(shè)置下降沿觸發(fā) EX0=1; //開(kāi)中斷 EA=1; //總中斷 KeyValue=0xFF; //鍵值初值 CH452_WriteCommand(0x0700); //2線接口ACK CH452_WriteCommand(0x0403);//開(kāi)顯示、鍵盤 }
void CH452_GetKeyValue()interrupt 0 { uchar i; uchar GetKeyValue=0x00; //鍵盤代碼 CH452_I2c_Start(); CH452_I2c_WrByte(((0x0700>>7)&0x3E)|0x41); GetKeyValue=CH452_Read(); CH452_I2c_Stop(); if(GetKeyValue==0x00) return; //讀出鍵碼為0跳過(guò) for(i=0;i<16;i++) { //查找鍵盤代碼對(duì)應(yīng)的鍵值 if(GetKeyValue==KeyCode[i]) { KeyValue=i; break; } } } void main { CH452_Init(); lcd_init(); if(KeyValue==0x40) { write_lcd(0,0,"0"); }