📄 untitled.c
字号:
//__CONFIG(0x3FFB);
# define DQ RA4 //定义18B20数据端口
# define SETDQ TRISA4 //定义18B20D口方向寄存器
# define FALSE 0
# define TRUE 1
# include <pic.h>
# define uch unsigned char
# define unint unsigned int
unsigned char a[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f}; //0到F的16个键植
int buffer[5]={0x00,0x00,0x00,0x00,0x00};
void delay_1us(void) //1us延时函数
{
asm("nop");
asm("nop");
}
void delay(unsigned int n) //N us延时函数
{
while(n--);
}
bit reset() //初始化18B20
{ unsigned char i;
static bit presence; //定义一个应答信号
SETDQ=1;
SETDQ=0; //定义为输出线
DQ=0; //刷新 避免干扰
delay(42); //置总线为低电平并保持至少480us
SETDQ = 1; //拉高总线
//等电阻拉高总线并保持15-60us
delay(2);
if(!DQ);
i=1;
delay(2) ;
presence=DQ; //接受应答信号
delay(30); //延时60-240us
if(i||presence)
return (FALSE);
return (TRUE); //返回应答信号
}
//*************** 读一位函数******************//
bit read_bit()
{
unsigned char sampling=2;
SETDQ=0;
while(--sampling);
SETDQ=1;
sampling=0;
NOP();NOP();NOP();NOP();
if(DQ)sampling++;NOP();NOP();NOP();NOP();
if(DQ)sampling++;NOP();NOP();NOP();NOP();
if(DQ)sampling++;
delay(2);
if(sampling>=2)
return 1;
return 0;
}
//*********************写一位函数****************//
bit write_bit(uch bitval)
{ uch sampling=0;
SETDQ=0;
NOP();NOP();NOP();NOP();
if(bitval&0x01)
SETDQ=1;NOP();NOP();NOP();NOP();
if(DQ)sampling++;NOP();NOP();NOP();NOP();
if(DQ)sampling++;NOP();NOP();NOP();NOP();
if(DQ)sampling++;
delay(2);
sampling=(sampling>=2);
SETDQ=1;
if(sampling==bitval)
return (TRUE);
return (FALSE);
}
//************** 从18B20中读一个字节**************//
uch read_byte()
{
unsigned char i;
uch value=0;
for (i=8;i!=0;i--)
{ value>>=1;
if(read_bit())
value|=0x80;
delay(4);
} //否则置 0
return(value);
}
//*********************向18B20中 写一个字节**************//
uch write_byte(uch dat)
{
uch i;
for(i=8;i!=0;i--)
{
if(!write_bit(dat&0x01))
return FALSE;
dat>>=1;
}
return TRUE;
}
unsigned int read ()
{
unsigned char temh,teml;
unsigned int value=0x550;
while(reset()); //复位等待从机应答
write_byte(0XCC); //忽略ROM匹配
write_byte(0X44); //发送温度转化命令
delay(20); //延时100-300us
while(reset()); //再次复位,等待从机应答
write_byte(0XCC); //忽略ROM匹配
write_byte(0XBE); //发送读温度命令
teml =read_byte(); //读出温度低8
temh=read_byte(); //读出温度高8位
SETDQ=1;
value =teml>>4 ; // 低字节
value += temh<<4; // 高字节
// value=789;
return(value);
}
main()
{
unsigned int temp;
TRISB=0x0;
TRISD=0x0;
temp=read();
buffer[0]=temp/100;
temp=temp%100;
buffer[1]=temp/10;
temp=temp%10;
buffer[2]=temp;
RB0=1;
PORTD=a[buffer[0]];//delay(100);
RB0=0;
delay(100);
RB1=1;
PORTD=a[buffer[1]];//delay(100);
RB1=0;
delay(100);
RB2=1;
PORTD=a[buffer[2]];//delay(100);
RB2=0;
delay(100);
RB3=1;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -