配色: 字号:
LCD1602单片机程序
2012-07-19 | 阅:  转:  |  分享 
  




#include"reg52.h"

#include"intrins.h"



#defineucharunsignedchar

#defineuintunsignedint



sbitRS=P2^0; //选择是数据还是指令

sbitRW=P2^1; //选择是读操作还是写操作

sbitE=P2^2; //使能信号

sbitBF=P0^7; //忙碌状态标志位

uchartemp;

//

voiddelay(uintz) //大约1ms的延时

{

ucharx,y;

for(x=z;x>0;x--)

for(y=110;y>0;y--);

}

//

bitRead_busy_flag() //读取忙碌标志位

{

bitresult;

RS=0;

RW=1; //进行读操作

E=1; //允许读数据

_nop_();

result=BF;

E=0;

returnresult;

}

//

voidWrite_instruction(ucharorder)

{

while(Read_busy_flag()==1);

RS=0;

RW=0; //给液晶写入指令

E=0;

_nop_();

P0=order;//将指令写入液晶

_nop_();

E=1;

_nop_();

E=0; //此时液晶就顺利接收到数据了

}

//

voidWrite_data(uchardat)

{

while(Read_busy_flag()==1);

RS=1;

RW=0; //给液晶写入数据

E=0;

_nop_();

P0=dat; //将数据写入液晶

_nop_();

E=1;

_nop_();

E=0; //此时液晶就顺利接收到数据了

}

//

voidInitialize() //芯片的初始化过程

{

delay(15);

Write_instruction(0x38);

delay(15);

Write_instruction(0x38);

delay(15);

Write_instruction(0x38);

delay(5);

Write_instruction(0x0f); //打开显示屏,有光标出现而且光标闪烁

delay(5);

Write_instruction(0x06); //写入数据后光标右移,显示屏不移动

delay(5);

Write_instruction(0x01); //清显示屏

delay(5);

}

//

voidsend_back() //数据返回子程序

{

SBUF=temp;

while(!TI); //等待数据发送完毕

TI=0; //将发送标志位清零

}

//

voidmain(void)

{

Initialize();

delay(10);

TMOD=0x20; //定时器1,工作方式2

TH1=0xfd;

TL1=0xfd; //给定时器1装初值,设定波特率为9600bps

PCON=0x00; //波特率不进行加倍

SM0=0;

SM1=1; //串行工作方式1

REN=1; //允许接收数据

ES=1; //打开串口中断4

TR1=1; //启动定时器1

EA=1; //打开总中断

while(1);

}

//

voidUART()interrupt4 //串行口中断服务程序

{

if(RI==1) //液晶接收到数据时该位自动置为1。

{

RI=0;

temp=SBUF;

send_back(); //把接收到的数据返回到上位机

if(temp==01)

{

Write_instruction(0x01); //清显示屏

}

Write_data(temp); //上位机给液晶写数据

}

}













































献花(0)
+1
(本文系朽木轩首藏)