#include <STC15F2K60S2.h>
#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 1 using 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 <reg52.h>
#define LCD1602_DB P0
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); //清屏
}
|