📄 18b20.c
字号:
#include <msp430x14x.h>
#define DQ0 P3OUT&=~0x01
#define DQ1 P3OUT|=0x01
#define uchar unsigned char
#define uint unsigned int
void DelayNus(uint n)
{
CCR0=n;
TACTL|=MC_1;//增计数
while(!(TACTL&BIT0));//等待
TACTL&=~MC_1;//停止计数
TACTL&=~BIT0;//清除中断标志
}
uchar Init_DS18B20(void)
{
uchar Error;
_DINT();
DQ0;
DelayNus(500);
DQ1;
DelayNus(55);
P3DIR&=~BIT0;
_NOP();
if(P1IN&BIT6)
{
Error=1;
P3DIR|=BIT0;
}
else
{
Error=0;
P3DIR|=BIT0;
}
_EINT();
DelayNus(400);
return Error;
}
void WriteOneChar(uchar wdata)
{
uchar i;
_DINT();
for(i=0;i<8;i++)
{
DQ0;
DelayNus(6);//延时6us
if(wdata&0x01) DQ1;
else DQ0;
wdata>>=1;
DelayNus(50);//延时50us
DQ1;
DelayNus(10);//延时10us
}
_EINT();
}
uchar ReadOneChar(void)
{
uchar i;
uchar temp=0;
_DINT();
for(i=0;i<8;i++)
{
temp>>=1;
DQ0;
DelayNus(6);
DQ1;
DelayNus(8);
P3DIR&=~BIT0;
_NOP();
if(P3IN&BIT0) temp|=0x80;
DelayNus(45);
P3DIR|=BIT0;
DQ1;
DelayNus(10);
}
_EINT();
return temp;
}
//读取温度
unsigned char ReadTemperature(unsigned char *temp)
{
unsigned char templ4=0;
unsigned char temph4=0;
unsigned char temppot=0;
unsigned char tempa=0;
Init_DS18B20();
WriteOneChar(0xCC); // 跳过读序号列号的操作
WriteOneChar(0x44); // 启动温度转换
Init_DS18B20();
WriteOneChar(0xCC); //跳过读序号列号的操作
WriteOneChar(0xBE); //读取温度寄存器等(共可读9个寄存器) 前两个就是温度
templ4=ReadOneChar();
temph4=ReadOneChar();
//if(temph4>0x0f){temph4=~temph4;sign=1;}
temppot=(templ4&0x0f);
temppot=temppot*10/16;
templ4=templ4/16;
tempa=(templ4+temph4*16);
*temp++=tempa/10 ;
*temp++=(tempa%10);
//*temp++='.';
*temp++=temppot;
*temp='\0';
return tempa;
}
initSys()
{
uchar i;
BCSCTL1&=~XT2OFF;
do
{
IFG1&=~OFIFG;
for(i=0xff;i>0;i--);
}
while((IFG1&OFIFG));
BCSCTL2&=SELM_2+SELS;//MCLK&SCLK选择高频晶振
TACTL|=TASSEL_2+ID_3;//计数时钟选择SMCK=8MHZ,1/8分频
_EINT();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -