下面是我找的ds18b20的程序 我读出的数据全是0x00
#define CLR_DIR_1WIRE DDRC&=~BIT(0) //只要修改这里的参数就可以了!呵呵!
#define SET_DIR_1WIRE DDRC|=BIT(0) //里面什么都不用该!
#define CLR_OP_1WIRE PORTC&=~BIT(0)
#define SET_OP_1WIRE PORTC|=BIT(0)
#define CHECK_IP_1WIRE (PINC & 0x04) //检测
unsigned char wmh,wml;
#define BIT(X) (1 << X)
//延时程序:
//delay.h
/*-----------------------------------------------------------------------
延时函数
系统时钟:8M
-----------------------------------------------------------------------*/
static void delay_1us(void) //1us延时函数
{
asm("nop");
}
static void delay_nus(unsigned int n) //N us延时函数
{
unsigned int i=0;
for (i=0;i<n;i++)
delay_1us();
}
static void delay_1ms(void) //1ms延时函数
{
unsigned int i;
for (i=0;i<1140;i++);
delay_1us();
}
static void delay_nms(unsigned int n) //N ms延时函数
{
unsigned int i=0;
for (i=0;i<n;i++)
delay_1ms();
}
void init_1820()
{
SET_DIR_1WIRE; //设置PA2 为输出
SET_OP_1WIRE;
CLR_OP_1WIRE;
delay_nus(480); //480us以上
SET_OP_1WIRE;
CLR_DIR_1WIRE;
delay_nus(20); //15~60us
while(CHECK_IP_1WIRE);
SET_DIR_1WIRE;
SET_OP_1WIRE;
delay_nus(140); //60~240us
}
void write_1820(unsigned char x)
{
unsigned char m;
for(m=0;m<8;m++)
{
CLR_OP_1WIRE;
if(x&(1<<m)) //写数据了,先写低位的!
SET_OP_1WIRE;
else
{CLR_OP_1WIRE;}
delay_nus(40); //15~60us
SET_OP_1WIRE;
}
SET_OP_1WIRE;
}
unsigned char read_1820()
{
unsigned char temp,k,n;
temp=0;
for(n=0;n<8;n++)
{
CLR_OP_1WIRE;
SET_OP_1WIRE;
CLR_DIR_1WIRE;
k=(CHECK_IP_1WIRE); //读数据,从低位开始
if(k)
temp|=(1<<n);
else
temp&=~(1<<n);
delay_nus(50); //60~120us
SET_DIR_1WIRE;
}
return (temp);
}
unsigned char gettemp() //读取温度值
{
unsigned char temh,teml,wm0,wm1,wm2,wm3;
init_1820(); //复位18b20
write_1820(0xcc);
write_1820(0x44); // 发出转换命令
delay_nms(800);
init_1820();
write_1820(0xcc);
write_1820(0xbe); //发出读命令
teml=read_1820(); //读数据
temh=read_1820();
wm0=teml>>4;
wm1=temh<<4;
wm2=wm1+wm0; //16进制转10进制
wm3=wm2/100;
return wm2;
}
unsigned int get_temp(char num)
{
unsigned char temh,teml,wm0,wm1,wm2,wm3;
unsigned int temp = 0;
if(num & 1)
{
init_1820();
write_1820(0xcc); //发出读命令
write_1820(0xbe);
teml=read_1820(); //读数据
temh=read_1820();
wm0=teml>>4;
wm1=temh<<4;
wm2=wm1+wm0;
wm3=wm2/100;
temp = (10 * ((unsigned int)teml & 0x0f) / 16) << 8;
temp |= (unsigned int)(wm2 & 0xff);
return temp;
}
else
{
init_1820(); //复位18b20
write_1820(0xcc); // 发出转换命令
write_1820(0x44);
return(0xffff);
}
}
int main(void)
{
temp = gettemp();
USART_transmit(temp);
}
是什么原因呢 时序问题的话要怎么查呢 可以加Q 583084481 |