|
今天我也在做这个
读出来的数据是0
有点郁闷
#include
#define DQ1 P2OUT |= BIT4
#define DQ0 P2OUT &= ~BIT4
void delayms(unsigned int z) {
unsigned int x;
for (x = z; x > 0; x--) {
__delay_cycles(1000);
}
}
//写指令
void write_com(unsigned char com) {
P2OUT &= ~BIT1;
P1OUT = com;
delayms(5);
P2OUT |= BIT3;
delayms(5);
P2OUT &= ~BIT3;
}
//写数据
void write_data(unsigned char myData) {
P2OUT |= BIT1;
P1OUT = myData;
delayms(5);
P2OUT |= BIT3;
delayms(5);
P2OUT &= ~BIT3;
}
void write_string(char string[]){
int i = 0;
while(string != '\0'){
write_data(string);
i++;
}
}
void lcd_clean() {
write_com(0x01); //清屏
}
void init_lcd() {
P1DIR = 0xff;
P2DIR = 0xff;
P2OUT &= ~BIT2;
P2OUT &= ~BIT3; //写数据模式
write_com(0x38); //设置模式
write_com(0x0c); //后三位分别为 显示 光标 闪烁
write_com(0x06); //后两位分别为 光标移动(左右) 屏幕移动 (动或不动)
lcd_clean();
write_com(0x80);
}
void show(unsigned char run)
{
char string[] = "TEMPERATURE:";
write_string(string);
write_com(0x80+0x40);
if(run == 0){
write_string("error");
}
}
void showTemperature(unsigned int t)
{
unsigned char num1,num2;
num1 = t / 10;
num2 = t %10;
write_data(num1+48);
write_data(num2+48);
}
unsigned char init_18B20(void)
{
unsigned char Error = 0;
DQ0;
__delay_cycles(500);
DQ1;
__delay_cycles(60);
P2DIR &=~ BIT4;
_NOP();
if(P2IN & BIT4)
{
Error = 0; //初始化失败
P2DIR |= BIT4;
}
else
{
Error = 1; //初始化成功 P2DIR |= BIT4;DQ1;
}
__delay_cycles(400);
return Error;
}
unsigned char read_18B20(void)
{
unsigned char i;
unsigned char temp = 0;
P2DIR |= BIT4;
for(i = 0;i < 8;i++)
{
temp >>= 1;
DQ0;
__delay_cycles(1);
DQ1;
P2DIR &= ~BIT4;
_NOP();
if(P2IN & BIT4)
temp |= 0x80;
__delay_cycles(45); //延时45us
}
return temp;
}
void write_18B20(unsigned char wdata)
{
unsigned char i;
P2DIR |= BIT4;
for(i = 0; i < 8;i++)
{
DQ0;
__delay_cycles(10); //延时10us
if(wdata & 0X01)
DQ1;
else
DQ0;
__delay_cycles(40); //延时50us
DQ1;
__delay_cycles(2); //延时10us
wdata >>= 1;
}
}
unsigned int read_Temperature(void)
{
unsigned int tem;
union
{
char c[2];
int x;
} temp;
while(init_18B20() == 0);
write_18B20(0xCC);
write_18B20(0x44);
delayms(1000);
while(init_18B20() == 0);
write_18B20(0xCC);
write_18B20(0xBE);
//读取温度数据
temp.c[0]=read_18B20();
temp.c[1]=read_18B20();
tem=(unsigned int)(temp.x*0.0625);
return tem;
}
void main() {
WDTCTL = WDTPW + WDTHOLD;
if (CALBC1_1MHZ == 0xFF || CALDCO_1MHZ == 0xFF) {
while (1); // If cal const erased, 挂起
}
BCSCTL1 = CALBC1_1MHZ; // Set range
DCOCTL = CALDCO_1MHZ; // Set DCO step + modulation*/
BCSCTL2 = SELM_1 + DIVM_0;
TACTL |= TASSEL_2;
init_lcd();
show(init_18B20());
unsigned int t;
while (1)
{
t = read_Temperature();
showTemperature(t);
delayms(1000);
}
} |
|