溫度傳感器18B20(串口顯示)
[導(dǎo)讀][cpp] view plaincopy /*溫度傳感器18B20--串口顯示溫度*/ #include<reg52.h> #include <intrins.h> typedef unsigned char uint8; typedef unsigned int uint16; typedef
- /*溫度傳感器18B20--串口顯示溫度*/
- #include<reg52.h>
- #include <intrins.h>
- typedef unsigned char uint8;
- typedef unsigned int uint16;
- typedef char int8;
- typedef int int16;
- sbit DQ=P3^2; //溫度輸入口
- void nops()
- {
- _nop_();
- _nop_();
- _nop_();
- _nop_();
- }
- void delay(uint16 n)
- {
- while(n--);
- }
- void delay_ms(uint16 n)
- {
- uint8 m=120;
- while (n--)
- while (m--);
- }
- void DS18b20_reset(void)
- {
- bit flag=1;
- while (flag)
- {
- DQ = 1;
- delay(1); //7.5us
- DQ = 0;
- delay(50); //139.8us
- DQ = 1;
- delay(6); // 21us
- flag = DQ;
- }
- delay(45); //延時(shí)500us
- DQ=1;
- }
- /*
- * 18B20寫1個(gè)字節(jié)函數(shù)
- * 向1-WIRE總線上寫一個(gè)字節(jié)
- */
- void write_byte(uint8 val)
- {
- uint8 i;
- for (i=0; i<8; i++)
- {
- DQ = 1;
- _nop_(); //兩次傳送間隔大于1us
- DQ = 0;
- nops(); //4us
- DQ = val & 0x01; //最低位移出
- delay(6); //66us (30US)
- val >>= 1; //右移一位
- }
- DQ = 1;
- delay(1);
- }
- /*
- * 18B20讀1個(gè)字節(jié)函數(shù)
- * 從1-WIRE總線上讀取一個(gè)字節(jié)
- */
- uint8 read_byte(void)
- {
- uint8 i, value=0;
- for (i=0; i<8; i++)
- {
- value >>= 1;
- DQ=1;
- _nop_();
- DQ = 0;
- nops(); //4us
- DQ = 1;
- nops(); //4us
- if (DQ)
- value|=0x80;
- delay(6); //66us
- }
- DQ=1;
- return value;
- }
- /*
- * 啟動(dòng)溫度轉(zhuǎn)換
- */
- void start_temp_sensor(void)
- {
- DS18b20_reset();
- write_byte(0xCC); // 發(fā)Skip ROM命令
- write_byte(0x44);// 發(fā)轉(zhuǎn)換命令
- }
- /*
- * 讀出溫度
- */
- int16 read_temp(void)
- {
- uint8 temp_data[2]; // 讀出溫度暫放
- int16 temp;
- DS18b20_reset(); // 復(fù)位
- write_byte(0xCC); // 發(fā)Skip ROM命令
- write_byte(0xBE); // 發(fā)讀命令
- temp_data[0]=read_byte(); //溫度低8位
- temp_data[1]=read_byte(); //溫度高8位
- temp = temp_data[1];
- temp <<= 8;
- temp |= temp_data[0];
- temp >>= 4; //注意是移動(dòng)四位
- return temp;
- }
- /**
- * UART初始化
- * 波特率:9600
- */
- void uart_init(void)
- {
- TMOD = 0x21; // 定時(shí)器1工作在方式2(自動(dòng)重裝)
- SCON = 0x50; // 10位uart,允許串行接受
- TH1 = 0xFD;
- TL1 = 0xFD;
- TR1 = 1;
- }
- /**
- * UART發(fā)送一字節(jié)
- */
- void UART_Send_Byte(uint8 dat)
- {
- SBUF = dat;
- while (TI == 0);
- TI = 0;
- }
- /**
- * 將數(shù)據(jù)轉(zhuǎn)換成ASC碼并通過UART發(fā)送出去
- */
- void UART_Send_Dat(uint8 dat) //100度以下溫度可用
- {
- UART_Send_Byte(dat/10%10 + '0');
- UART_Send_Byte(dat%10 + '0');
- }
- main()
- {
- int16 ans;
- uart_init();
- start_temp_sensor();
- while (1)
- {
- delay_ms (1000); // 延時(shí)1秒
- ans=read_temp();
- if (ans < 0)
- {
- UART_Send_Byte('-');
- ans = -ans;
- }
- UART_Send_Dat(ans);
- UART_Send_Byte('r');
- UART_Send_Byte('n');
- }
- }





