I2C通信以及51单片机读写字符串利用LCD12864显示程序
#include <reg51.h>
#include <intrins.h>
#define READCOMDE 0xa1
#define WRITECOMDE 0xa0
#define uchar unsigned char
#define uint unsigned int
#define port P0
unsigned char code table[]={0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01};
const unsigned char dattable[]={"helloworldhelloworld!"};
#define size sizeof(dattable)
sbit e=P2^7;
sbit rw=P2^5;
sbit rs=P2^6;
sbit rst=P3^4;
sbit psb=P3^2;
sbit SDA=P2^0;
sbit SCL=P2^1;
void delay_50us (uint n)
{ uint i;
for( ;n>0;n--)
for(i=19;i>0;i--);
}
void delay_50ms (uint n)
{ uint i;
for( ;n>0;n--)
for(i=6245;i>0;i--);
}
void comd(uchar com)
{
rs=0;
rw=0;
delay_50us(1);
port=com;
e=1;
delay_50us(10);
e=0;
delay_50us(2);
}
void date(uchar dat)
{
rs=1;
rw=0;
delay_50us(1);
port=dat;
e=1;
delay_50us(10);
e=0;
delay_50us(2);
}
void init(void)
{
psb=1;
rst=1;
delay_50ms(2);
comd(0x30);
delay_50us(4);
comd(0x30);
delay_50us(4);
comd(0x0f);
delay_50us(4);
comd(0x01);
delay_50us(240);
comd(0x06);
delay_50us(10);
}
void delay1ms()
{
unsigned char i,j;
for(i=0;i<10;i++)
for(j=0;j<33;j++);
}
void delay()
{ ;; }
void delaynms(int n)
{
int i;
for(i=0;i<n;i++)
delay1ms();
}
void startiic()
{
SDA=1;
delay();
delay();
SCL=1;
delay();
SDA=0;
delay();
SCL=0;
delay();
}
unsigned char readbit8()
{
unsigned char i;
unsigned char dat=0;
for(i=0;i<8;i++)
{
SCL=1;
dat<<=1;
dat|=(unsigned char)SDA;
SCL=0;
delay();
}
return(dat);
}
void writebit8(unsigned char dat)
{
unsigned char i;
for(i=0;i<8;i++)
{
SDA=(bit)(dat&0x80);
delay();
SCL=1;
dat<<=1;
delay();
SCL=0;
}
}
bit ack()
{
bit a;
SDA=1;
SCL=1;
delay();
a=SDA;
SCL=0;
return(a);
}
void stopiic()
{
SDA=0;
delay();
SCL=1;
delay();
SDA=1;
delay();
}
unsigned char readdate(unsigned char address)
{
unsigned char dat;
startiic();
writebit8(WRITECOMDE);
ack();
writebit8(address);
ack();
startiic();
writebit8(READCOMDE);
ack();
dat=readbit8();
stopiic();
return dat;
}
void writedate(unsigned char address,unsigned char dat)
{
startiic();
writebit8(WRITECOMDE);
ack();
writebit8(address);
ack();
writebit8(dat);
ack();
stopiic();
delaynms(2);
}
void read(unsigned char address,unsigned char *dat,unsigned char len)
{
while(len)
{
*dat++=readdate(address++);
len--;
}
}
void write(unsigned char address,unsigned char *dat,unsigned char len)
{
while(len--)
{
writedate(address,*dat);
address++;
dat++;
}
}
void main()
{
unsigned char receivedate[size];
init();
while(1)
{
uchar i=0;
write(8,(unsigned char*)dattable,size);
read(8,receivedate,size);
delaynms (1000);
comd(0x80);
for(i=0;i<size;i++)
{
date(receivedate[i]);
delay_50us(1);
}
}
}
|