HC_SR04超声波测距程序

HC_SR04超声波测距程序_第1张图片

//主要代码

/hr04.h文件/

#ifndef _LCD1602_H_
#define _LCD1602_H_
#include 

#define LCD1602_DB P0

sbit LCD1602_RS = P1^0;
sbit LCD1602_RW = P1^1;
sbit LCD1602_E = P1^5;

/**等待液晶准备好**/
void Lcdwaitready();

/**向LCD1602写入一个字节命令,cmd-待写入命令值**/
void LcdWriteCmd(unsigned char cmd);

/**向LCD1602液晶写入一字节数据,dat—待写入数据**/
void LcdWriteDat(unsigned char dat);

/**设置显示RAM起始地址,即光标位(X,Y)**/
void LcdSetCursor(unsigned char x,unsigned char y);

/*在液晶上显示字符串*/
void LcdShowStr(unsigned char x,unsigned char y,unsigned char *str);

/*液晶输出数字*/
void LCDNumPrint(unsigned num);

/*初始化LCD1602液晶*/
void InitLcd1602();

#endif

/hr04.c文件/

#include "lcd1602.h"

/**等待液晶准备好**/
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);
}

/**向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 address;
	if(y == 0){
		address = 0x00 + x;
	}else{
		address = 0x40 + x;
	}
	LcdWriteCmd(address | 0x80);
}

/*在液晶上显示字符串*/
void LcdShowStr(unsigned char x,unsigned char y,unsigned char *str){
	LcdSetCursor(x,y);
	while(*str != '\0'){
		LcdWriteDat(*str++);
	}
}

/*液晶输出数字*/
void LCDNumPrint(unsigned int num)
{
        //LcdWriteDat(num/1000 + 0x30);//num的千位//因为LCD1602显示的数字0,是用0x30表示的,也可以把0当做字符显示
        LcdWriteDat(num % 1000 / 100 + 0x30);//num的百位
        LcdWriteDat(num % 100 /10 + 0x30);//num的十位
				LcdWriteDat('.');//num的个位
        LcdWriteDat(num % 10 + 0x30);//num的个位
				
}

/*初始化LCD1602液晶*/
void InitLcd1602(){
	LcdWriteCmd(0x38);//16*2显示 5*7点阵,8位数据接口
	LcdWriteCmd(0x0c);//显示器开,光标关闭
	LcdWriteCmd(0x06);//文字不动,地址自动加1
	LcdWriteCmd(0x01);//清屏
}


/lcd1602.h/
/lcd1602.c/
(此处省略,可参考之前博客的代码)

/main.c文件/

#include "lcd1602.h"
#include "hr04.h"

void InitLcd1602();
void LcdShowStr(unsigned char x,unsigned char y,unsigned char *str);
void LCDNumPrint(unsigned num);
void LcdSetCursor(unsigned char x,unsigned char y);
uint GetDistance(void);

void main()
{
        uint dist;
        InitLcd1602();
				
        TMOD = 0x01;
        LcdShowStr(0,0,"The Distance is:");
        LcdShowStr(4,1,"cm");
        while(1)
        {
                dist = GetDistance();
                LcdSetCursor(0,1);
                LCDNumPrint(dist);
        }
				
       
}

你可能感兴趣的:(HC_SR04超声波测距程序)