bit dat=0; DQ = 1; DelayUs2x(5); DQ = 0; DelayUs2x(200); DelayUs2x(200); DQ = 1; DelayUs2x(50); dat=DQ; DelayUs2x(25); return dat; }
unsigned char ReadOneChar(void) //{
unsigned char i=0; unsigned char dat = 0; for (i=8;i>0;i--) {
DQ = 0; // 给脉冲信号 dat>>=1;
DQ = 1; // 给脉冲信号 if(DQ) dat|=0x80; DelayUs2x(25); }
return(dat); }
从18b20读取一字节数据28
void WriteOneChar(unsigned char dat) //向18b20写入一个字节数据 {
unsigned char i=0; for (i=8; i>0; i--) { DQ = 0; DQ = dat&0x01; DelayUs2x(25); DQ = 1; dat>>=1; }
DelayUs2x(25); }
unsigned int ReadTemperature(void) //温度读取主程序 {
unsigned char a=0; unsigned int b=0; unsigned int t=0; Init_DS18B20();
WriteOneChar(0xCC); // 跳过读序号列号的操作 WriteOneChar(0x44); // 启动温度转换 DelayMs(10); Init_DS18B20();
WriteOneChar(0xCC); //跳过读序号列号的操作
WriteOneChar(0xBE); //读取温度寄存器等(共可读9个寄存器)a=ReadOneChar(); //低位 b=ReadOneChar(); //高位
29
前两个就是温度
b<<=8; t=a+b;
return(t); //返回两字节温度值 }
1.3解码程序
接收单片机: #include \
sbit led=P1^1; sbit wuxian=P3^2; sbit mingdi=P1^2;
void DelayMs(unsigned int t); main() {
mingdi=0; led=1; wuxian=0; while(1) {
while(!wuxian); //循环等待无线信号
DelayMs(200); //延时再重测,以消除噪声电平导致的误动作 if(wuxian) //延时200ms再次检测检测到高电平,则说明不是噪声电平
{
30
mingdi=1; //蜂鸣器响,led亮 led=0; while(wuxian);
DelayMs(5000); //由于J04v接收到的是一段较短的脉冲,此处用软件延时5s的 //方法实现蜂鸣器的长响 mingdi=0; //蜂鸣器停止,led灭 led=1; } } }
void DelayUs2x(unsigned char t) { while(--t); }
void DelayMs(unsigned int t) //1ms{
while(t--) {
//大致延时1mS DelayUs2x(245); DelayUs2x(245);
} }
2 器件简介
2.1温度传感器DS18b20介绍:
延时程序 31
相关推荐: