#include
#define u8 unsigned char
#define u16 unsigned int
sbit PWM = P1^0;
extern void InitLcd1602();
extern void LcdShowStr(unsigned char x, unsigned char y,unsigned char *str, unsigned char len);
u8 Trg,Cont; //独立按键
#define KEYPROUT P3
void key_read(void)
{
u8 ReadData = KEYPROUT^0xff;
Trg = ReadData&(ReadData^Cont);
Cont = ReadData;
}
void Timer0_Init(void) //1ms 定时器0初始化
{
AUXR |= 0x80; //1T timer
TMOD &= 0xF0; // 16bit
TL0 = 0xCD;
TH0 = 0xD4;
TF0 = 0;
TR0 = 1;
ET0 = 1;
EA=1;
}
void Timer1Init(void)//100微秒@11.0592MHz
{
AUXR |= 0x40;//定时器时钟1T模式
TMOD &= 0x0F;//设置定时器模式
TL1 = 0xAE;//设置定时初值
TH1 = 0xFB;//设置定时初值
TF1 = 0;//清除TF1标志
TR1 = 1;//定时器1开始计时
ET1 = 1;
}
bit key_flag,timer_500ms_flag;
u8 pwm_set=5;
u8 str[15];
void main(void)
{
P2=0xa0;P0=0x00;P2=0x00; // 关闭蜂鸣器
Timer0_Init(); //1ms 定时器0初始化
Timer1Init();
InitLcd1602();
while(1)
{
if(timer_500ms_flag)
{
timer_500ms_flag=0;
LcdShowStr(0,0,str,1);
}
str[0] = pwm_set + '0';
if(key_flag) // 按键扫描
{
key_flag=0;
key_read();
if(Trg&0x08)//s4
{
pwm_set++;
}
if(Trg&0x04)//s5
{
pwm_set--;
}
if(Trg&0x02)//s6
{
}
if(Trg&0x01)//s7
{
}
if(Cont) //按键按下
{
}
if(Trg==0&Cont==0) //按键放开
{
}
}
}
}
void timer0() interrupt 1using 1
{
static int key_count=0,timer_500ms=0;
key_count++;timer_500ms++;
if(key_count==10) //10ms 按键扫描
{
key_count=0;
key_flag=1;
}
if(timer_500ms==500)
{
timer_500ms=0;
timer_500ms_flag=1;
}
}
void timer1() interrupt 3
{
static u8 pwm_count=0;
pwm_count++;
if(pwm_count==pwm_set)
{
PWM=0;
}
if(pwm_count==10)
{
pwm_count=0;
PWM=1;
}
}
#include
#define LCD1602_DBP0
sbit LCD1602_RS = P2^0;
sbit LCD1602_RW = P2^1;
sbit LCD1602_E= P1^2;
/* 等待液晶准备好 */
void LcdWaitReady()
{
unsigned char sta;
LCD1602_DB = 0xFF;
LCD1602_RS = 0;
LCD1602_RW = 1;
do {
LCD1602_E = 1;
sta = LCD1602_DB; //读取状态字
LCD1602_E = 0;
} while (sta & 0x80); //bit7等于1表示液晶正忙,重复检测直到其等于0为止
}
/* 向LCD1602液晶写入一字节命令,cmd-待写入命令值 */
void LcdWriteCmd(unsigned char cmd)
{
LcdWaitReady();
LCD1602_RS = 0;
LCD1602_RW = 0;
LCD1602_DB = cmd;
LCD1602_E= 1;
LCD1602_E= 0;
}
/* 向LCD1602液晶写入一字节数据,dat-待写入数据值 */
void LcdWriteDat(unsigned char dat)
{
LcdWaitReady();
LCD1602_RS = 1;
LCD1602_RW = 0;
LCD1602_DB = dat;
LCD1602_E= 1;
LCD1602_E= 0;
}
/* 设置显示RAM起始地址,亦即光标位置,(x,y)-对应屏幕上的字符坐标 */
void LcdSetCursor(unsigned char x, unsigned char y)
{
unsigned char addr;
if (y == 0)//由输入的屏幕坐标计算显示RAM的地址
addr = 0x00 + x;//第一行字符地址从0x00起始
else
addr = 0x40 + x;//第二行字符地址从0x40起始
LcdWriteCmd(addr | 0x80);//设置RAM地址
}
/* 在液晶上显示字符串,(x,y)-对应屏幕上的起始坐标,
str-字符串指针,len-需显示的字符长度 */
void LcdShowStr(unsigned char x, unsigned char y,
unsigned char *str, unsigned char len)
{
LcdSetCursor(x, y); //设置起始地址
while (len--) //连续写入len个字符数据
{
LcdWriteDat(*str++);//先取str指向的数据,然后str自加1
}
}
/* 初始化1602液晶 */
void InitLcd1602()
{
LcdWriteCmd(0x38);//16*2显示,5*7点阵,8位数据接口
LcdWriteCmd(0x0C);//显示器开,光标关闭
LcdWriteCmd(0x06);//文字不动,地址自动+1
LcdWriteCmd(0x01);//清屏
}