//读状态,忙则循环,不忙则返回Data uchar ReadStatusLCM(void) {
uchar Data;
DDRA=0xff; //设置指令 PORTA=0xff;
DDRD=0xff;//1,输出,置数 0,输入,读数 ClrRS; SetRW;
SetE; //执行指令 SetE;
DDRA=0x00; //读忙标志,忙则循环 Data=PINA; while(Data&0x80) Data=PINA; return(Data); }
//写指令
void WriteCommandLCM(uchar WCLCM,uchar c) {
if(c==1) //标志为0不忙检测,标志为1检测 ReadStatusLCM();
DDRA=0xff; //设置指令 PORTA=WCLCM;
DDRD=0xff;//1,输出,置数 0,输入,读数 ClrRS; ClrRW;
SetE; SetE; ClrE; }
//读数据
/*uchar ReadDataLCM(void) {
ReadStatusLCM(); //忙检测
ClrRS; //指令设置 ClrRW;
ClrE; //执行指令 ClrE; SetE;
return(Data); }*/
//初始化
void LCMInit(void) {
DDRA=0xff; PORTA=0x00;
WriteCommandLCM(0x38,0);//三次显示设置 ,不需忙检 Delay5ms(); //四位总线,双行显示,5*7点阵 WriteCommandLCM(0x38,0); Delay5ms();
WriteCommandLCM(0x38,0); Delay5ms();
WriteCommandLCM(0x38,1);//显示模式设置,以后都须忙检 WriteCommandLCM(0x08,1);//关闭显示 WriteCommandLCM(0x01,1);//清屏
WriteCommandLCM(0x06,1);//光标右移,字符不移 WriteCommandLCM(0x0c,1);//显示开,有光标,有闪烁 }
//写数据
void WriteDataLCM(uchar WDLCM) {
ReadStatusLCM(); //忙检测
DDRA=0xff; //设置指令 PORTA=WDLCM;
DDRD=0xff;//1,输出,置数 0,输入,读数 SetRS; ClrRW;
SetE; SetE; ClrE; }
//按指定位置显示一个字符
void DisplayOneChar(uchar X,uchar Y,uchar DData) {
Y&=0x01;//Y不能>1 X&=0x0f;//X不能>15 if(Y)
X+=0x40;//显示第二行时地址码+0x40
X+=0x80;//计算指令码
WriteCommandLCM(X,0);//发送地址码不需忙检 WriteDataLCM(DData); }
//在指定位置显示字符串
void DisplayListChar(uchar X,uchar Y,uchar *DData) {
uchar pose=0;
Y&=0x01;//Y不能>1 X&=0x0f;//X不能>15
while(DData[pose]>0x20) {
DisplayOneChar(X,Y,DData[pose]);//显示单个字符 pose++;
X++; if(X>=0xF) {X=0x00; Y=0x01; } } }
void Delay1ms(void) {
uint time,i; time=5552; while(time--); }
//延时5ms,已验证 void Delay5ms(void) {
uint time,i; for(i=0;i<5;i++) {time=5552; while(time--); } }
//延时400ms
void Delay400ms(void) {
uchar j;
for(j=0;j<8;j++)//延时400ms {
Delay5ms(); } }
//////////TWI总线操作函数 ////////////
void Start(void) //TWSTA置位,产生START状态 {TWCR=(1< void Wait(void) //应用程序等待硬件操作完成 {while((TWCR&0x80)!=0x80);} //一直循环,直至硬件已置位TWINT unsigned char TestAck(void) //读并返回状态寄存器TWSR的状态位,屏蔽低三位 {unsigned char twsr; twsr=TWSR&0xf8; return twsr; } void Write8Bit(unsigned char data)//应用程序写数据到数据寄存器TWDR,清TWINT启动发送 {TWDR=data; TWCR=(1< void Stop(void) //TWSTO置位,产生STOP状态 {TWCR=(1< void Ack(void) //使能EA,如果接受到数据发送ACK脉冲 {TWCR=(1< void Twi(void) //使能TWI操作激活TWI接口 {TWCR=(1< // 向I2C总线写数据 ,正确写入数据返回0,否则分别返回2,3,4 unsigned char i2c_Write(unsigned char command,unsigned char RomAddress) { Start(); //发总线起始命令 Wait(); //等待应答 if(TestAck()!=START) return 1; //测试应答 Write8Bit(wr_device_add); //装入写器件地址 Wait(); //等待应答 if(TestAck()!=MT_SLA_ACK) return 2; //测试应答 Write8Bit(RomAddress); //装入写器件内的寄存器地址 Wait(); //等待应答 if(TestAck()!=MT_DATA_ACK) return 3; //测试应答 Write8Bit(command); //写命令 Wait(); //等待应答 if(TestAck()!=MT_DATA_ACK) return 4; //测试应答