本帖最后由 一君呀 于 2020-9-28 22:03 編輯
想做一個溫度顯示計,傳感器用的DS18b20,程序寫完了在開發板上試了結果液晶屏上是這個樣子,不知道是咋回事,有人能幫忙看一下么,拜托了這里是程序
IMG_20200928_212310.jpg (4.43 MB, 下載次數: 54)
下載附件
2020-9-28 21:27 上傳
第一次寫,可能有很多漏洞什么的,還請多多指教
單片機源程序如下:
#include <reg52.h>
#include <intrins.h>
typedef unsigned char u8;
typedef unsigned int u16;
#define LCD1602 P0
sbit DS = P3^7; //定義DS18B20的端口
sbit RS = P2^6; //lcd1602寄存器
sbit RW = P2^5; //讀寫
sbit EN = P2^7; //片選
void delay_us(u16 i) //微秒延時函數 ,不精確延時,i=1大約為10us
{
while(i--);
}
void delay1ms(u16 ms) //1毫秒延時函數
{
u16 i,j;
for (i=0;i<ms;i++);
for(j=0;j<120;j++);
}
void delay(u16 x) //延時函數
{
u16 i;
for(i=x;i>0;i--);
}
u8 DS18B20_CS() //DS18B20初始化
{
bit x;
u8 i = 0;
DS = 0; //拉低總線
i = 70;
while(i--); //延時642us
DS = 1;
i = 0;
delay_us(7);
x = DS;
delay_us(15);
DS = 1;
_nop_();
return(x);
}
void DS18B20_XSX(u8 i) //DS18B20寫時序
{
u8 y;
for(y=0;y<8;y++)
{
DS = 1;
_nop_();
DS = 0;
DS = i&0x01;
delay_us(7);
DS = 1;
_nop_();
_cror_(i,1);
}
}
u8 DS18B20_DSX() //讀時序
{
u8 x,y,z;
for(x=0;x<8;x++)
{
DS = 0;
_nop_();
DS = 1;
_nop_();
y = DS;
delay_us(7);
DS = 1;
_nop_();
z = (y<<7)|(z>>1); //從最低位開始讀取,循環8位
}
return(z);
}
void DS18B20_change() //轉換溫度
{
DS18B20_CS();
delay1ms(1);
DS18B20_XSX(0xcc);
DS18B20_XSX(0x44);
}
void DS18B20_FS() //發送溫度
{
DS18B20_CS();
delay1ms(1);
DS18B20_XSX(0xcc);
DS18B20_XSX(0xbe);
}
int DS18B20_DQ() //讀取溫度
{
int temp = 0;
u8 H,L;
DS18B20_change();
DS18B20_FS();
L=DS18B20_DSX(); //從低8位開始讀
H=DS18B20_DSX(); //高8位
temp = H;
temp<<=8;
temp |= L;
return temp;
}
void LCD1602_com(u8 com) //LCD1602寫指令函數
{
RS = 0;
RW = 0;
EN = 0;
P0 = com;
delay1ms(1);
EN = 1;
delay1ms(5);
EN = 0;
}
void LCD1602_dat(u8 dat) //寫數據函數
{
P0 = dat; //送出時序
RS = 1;
RW = 0;
EN = 1;
delay(200);
EN = 0;
}
void LCD1602_init() //初始化
{
LCD1602_com(0x01); //初始化
LCD1602_com(0x38); //清屏
LCD1602_com(0x0c); //開顯示。不顯示光標
LCD1602_com(0x06); //地址加1寫入數據時光標右移
LCD1602_com(0x87); //起始位置
}
void LCD1602_disp(int temp) //顯示函數
{
u8 table[] ={0,0,0,0};
float i;
LCD1602_com(0x80);
i = temp;
temp = i*0.0625*10+0.5;
table[0]=temp/100;
table[1]=temp/10%10;
table[2]=temp%10;
LCD1602_com(0x87); //顯示第一位數的位置
LCD1602_dat('0'+table[0]);
LCD1602_com(0x88); //顯示個位
LCD1602_dat('0'+table[1]);
LCD1602_com(0x89); //顯示小數點
LCD1602_dat('.');
LCD1602_com(0x0A); //小數后一位
LCD1602_dat('0'+table[2]);
delay(50);
}
void main()
{
LCD1602_init();
LCD1602_com(0x88);
while(1)
{
LCD1602_disp( DS18B20_DQ());
}
}
|