当前位置:网站首页>STM32 entry development write DS18B20 temperature sensor driver (read ambient temperature, support cascade)

STM32 entry development write DS18B20 temperature sensor driver (read ambient temperature, support cascade)

2022-07-07 11:22:00 Hua Weiyun

One 、 Introduction to the environment

Programming software : keil5

operating system : win10

MCU model : STM32F103C8T6

STM32 programmatically : Register development ( It is convenient to transplant the program to other single chip computers )

Temperature sensor : DS1820

DS18B20 It is a digital temperature sensor , It adopts single bus timing to communicate with the host , Only one wire is needed to read the temperature data ;

DS18B20 Built in 64 Bit product serial number , Easy identification , You can connect more than one on one line DS18B20 sensor , adopt 64 Bit authentication , The temperature information collected from different sensors can be read separately .
image.png
image.png

Two 、DS18B20 Introduce

2.1 DS18B20 The main characteristics of

\1. Full digital temperature conversion and output .

\2. Advanced single bus data communication .

\3. The highest 12 Bit resolution , The accuracy can reach 0.5 Centigrade .

\4. 12 The maximum duty cycle at bit resolution is 750 millisecond .

\5. Optional parasitic working mode .

\6. The detection temperature range is –55° C ~+125° C (–67° F ~+257° F)

\7. built-in EEPROM, Temperature limit alarm function .

\8. 64 Bit lithography ROM, Built in product serial number , Convenient multi machine hook up .

\9. Various packaging forms , Adapt to different hardware systems .
image.png

2.2 DS18B20 Pin function

GND Voltage to ground

DQ Single data bus

VDD Supply voltage

NC Empty pin

2.3 DS18B20 Working principle and Application

​ DS18B20 The temperature detection and digital data output are integrated on one chip , Thus, the anti-interference ability is stronger . A work cycle can be divided into two parts , That is, temperature detection and data processing .

18B20 There are three types of memory resources , They are :ROM read-only memory , To hold DS18B20ID code , Before that 8 Bit is a single line serial code (DS18B20 The code of is 19H), Back 48 Bit is the unique serial number of the chip , Last 8 Bit is above 56 A bit of CRC code ( Redundancy check ). The setting of data during production is not changed by the user ,DS18B20 Altogether 64 position ROM.

RAM Data register , For internal computing and data access , Data is lost after power failure , DS18B20 common 9 Bytes RAM, Each byte is 8 position . The first 1、 2 Bytes are the data value information after temperature conversion , The first 3、 4 Bytes are user EEPROM( It is commonly used for temperature alarm value storage ) Mirror image . Its value will be refreshed during power on reset . The first 5 The first byte is the user's... Th byte 3 individual EEPROM Mirror image . The first 6、 7、 8 Bytes are count registers , It is designed to allow users to get higher temperature resolution , It is also an internal temperature conversion 、 Temporary storage unit for calculation . The first 9 The first byte is 8 Bytes of CRC code . EEPROM Nonvolatile memory , It is used to store data that needs to be saved for a long time , Upper and lower temperature alarm values and calibration data ,DS18B20 common 3 position EEPROM, And in RAM There are mirrors , In order to facilitate user operation .
image.png

DS18B20 Default works at 12 Bit resolution mode , What you get from the conversion is 12 Bit data , Stored in DS18B20 Of the two 8 Bit RAM in ( The first two bytes ), Front in binary 5 Bits are sign bits , If the measured temperature is greater than 0, this 5 Position as 0, Just multiply the measured value by 0.0625 You can get the actual temperature ; If the temperature is less than 0, this 5 Position as 1, The measured value needs to be added inversely 1 Multiply again 0.0625 You can get the actual temperature . Or use bit operation to extract temperature : Decimal places are low 4 position , The high order is integer ( Regardless of negative numbers ).

2.4 DS18B20 chip ROM Instruction list

1. Read ROM( read ROM) [33H] ( In square brackets is 16 Hexadecimal command word )
This command allows the bus controller to read DS18B20 Of 64 position ROM. Only if there is only one... On the bus DS18B20 This command can only be used when , If more than one is attached , When communicating, data conflicts will occur

2. atch ROM( Specify the matching chip ) [55H]
This command is followed by the controller 64 A serial number , When there are multiple on the bus DS18B20 when , Only the same chip as the serial number sent by the control can respond , Other chips will wait for the next reset . This instruction is suitable for single chip and multi chip hooking .

3. Skip ROM( jumping ROM Instructions ) [CCH]
This instruction makes the chip wrong ROM Code to respond , In the case of a single bus , To save time, you can choose this command . If this instruction is used during multi chip hooking, there will be data conflict , Cause an error to occur .

4. Search ROM( Search chip ) [F0H]
After chip initialization , The search instruction allows the elimination method to identify all devices when multiple chips are attached to the bus 64 position ROM.

5. Alarm Search( Alarm chip search ) [ECH]
In the case of multi chip hooking , The alarm chip search command only applies to the attachment temperature higher than TH Or less than TL The chip of the alarm condition reacts . As long as the chip doesn't lose power , The alarm state will be maintained , Until the temperature can not even reach the alarm condition again .

6. Write Scratchpad ( towards RAM Write data in ) [4EH]
This is to RAM Instructions for writing data in , The two bytes of data written later will be stored in the address 2( Call the police RAM And TH) And address 3( Call the police RAM And TL). During the writing process, you can use the reset signal to stop writing .

7. Read Scratchpad ( from RAM Middle reading data ) [BEH]
This instruction will start from RAM Middle reading data , Read address from address 0 Start , You can always read the address 9, Complete the entire RAM Data readout . The chip allows the reading to be aborted with a reset signal during the reading process , That is, the following unnecessary bytes can not be read to reduce the reading time .

8. Copy Scratchpad ( take RAM Copy data to EEPROM in ) [48H]
This command will RAM Data stored in EEPROM in , So that the data will not be lost after power failure . Since then, the chip is busy EEPROM Storage and handling , When the controller sends a read time slot , Output on the bus “0”, When storage is complete , The bus will output “1”.
In the parasitic working mode, the super strong pull-up must be used immediately after this command is issued, and at least 10MS, To keep the chip working .

9. Convert T( Temperature conversion ) [44H]
After receiving this command, the chip will perform a temperature conversion , Put the converted temperature value into RAM Of the 1、 2 Address . Since then, the chip is busy with temperature conversion processing , When the controller sends a read time slot , Output on the bus “0”, When storage is complete , The bus will output “1”. In the parasitic working mode, the super strong pull-up must be used immediately after this command is issued, and at least 500MS, To keep the chip working .

10. Recall EEPROM( take EEPROM The alarm value in is copied to RAM) [B8H]
This command will EEPROM The alarm value in is copied to RAM No 3、 4 In a byte . Because the chip is busy copying , When the controller sends a read time slot , Output on the bus “0”, When storage is complete , The bus will output “1”. in addition , This instruction will be automatically executed when the chip is powered on and reset . such RAM The two alarm byte bits in will always be EEPROM Image of data in .

11. Read Power Supply( Working mode switching ) [B4H]
After this command is issued, a read time slot is issued , The chip will return its power status word ,“0” It is in parasitic power state ,“1” Is the external power state .

2.5 DS18B20 Sequence diagram

2.5.1 DS18B20 Diagram of reset and response relationship

image.png
image.png

It must be reset before each communication , Reset time 、 Waiting time 、 The response time shall be programmed strictly according to the sequence .

DS18B20 Read / write time gap :DS18B20 The data reading and writing of is to confirm the information exchange through time slot processing bits and command words .

2.5.2 towards DS18B20 Writing data 0 And data 1

image.png

Before writing the data time slot 15uS The bus needs to be pulled low by the controller , Then it will be the sampling time of the chip to the bus data , The sampling time is 15~60uS, If the controller pulls the bus high during the sampling time, it means write “1”, If the controller pulls the bus down, it means write “0”.

Each bit should be sent with at least one 15uS Low level start bit of , Subsequent data “0” or “1” belong 45uS Finish in .

The transmission time of the whole bit should be kept at 60~120uS, Otherwise, the normal communication cannot be guaranteed .

Be careful : DS18B20 Read and write data are transmitted from the low bit .

2.5.3 from DS18B20 Reading data 0 And data 1

image.png

The sampling time of time slot reading control should be more accurate , When reading the time slot, the host must first generate at least 1uS Low level of , Indicates the beginning of the reading time . Then after the bus is released 15uS in DS18B20 Internal data bits will be sent , At this time, if the control finds that the bus is high, it indicates that it reads “1”, If the bus is low, it means that the data is read “0”. Before reading each bit, the controller adds a start signal .

Be careful : It must start at the reading gap 15uS The correct communication can only be ensured by reading data bits inside .

When communicating, we use 8 position “0” or “1” For a byte , Bytes are read or written from the low order .

2.5.4 Read the sequence of temperature once ( There is only one on the bus DS18B20 situation )

\1. Send a reset signal

\2. Detect the response signal

\3. send out 0xCC

\4. send out 0x44

\5. Send a reset signal

\6. Detect the response signal

\7. Write 0xcc

\8. Write 0xbe

\9. loop 8 Read the low temperature byte for times

\10. loop 8 Read the high temperature byte for times

\11. synthesis 16 Bit temperature data , Handle

3、 ... and 、 Driver code

3.1 DS18B20.c

#include "ds18b20.h"/* The functionality : DS18B20 Initialize the hardware connection : PB15*/void DS18B20_Init(void){		RCC->APB2ENR|=1<<3; //PB		GPIOB->CRH&=0x0FFFFFFF;		GPIOB->CRH|=0x30000000;		GPIOB->ODR|=1<<15; // Pull up }/* The functionality :  testing DS18B20 Whether the device has a return value  : 1 Indicates that the device does not exist  0 Indicates that the equipment is normal */u8 DS18B20_CheckDevice(void)  // Contains reset pulse 、 Detect the presence of pulses {		DS18B20_OUTPUT_MODE();// Initialize to output mode 		DS18B20_OUT=0;        // Generate reset pulse 		DelayUs(750);         // produce 750us Low level of 		DS18B20_OUT=1;        // Release the bus 		DelayUs(15);          // wait for DS18B20 Respond 		if(DS18B20_CleckAck())// Detect the presence of pulses 		{				return 1;		}		return 0;}/* The functionality :  testing DS18B20 The existence pulse return value of the device  : 1 Indicates an error  0 Is normal */u8 DS18B20_CleckAck(void){		u8 cnt=0;		DS18B20_INPUT_MODE();// Initialize to input mode 		while(DS18B20_IN&&cnt<200) // wait for DS18B20 There is a pulse in the response 		{				DelayUs(1);				cnt++;		}		if(cnt>=200)return 1; // error 				cnt=0;		while((!DS18B20_IN)&&cnt<240) // wait for DS18B20 Release the bus 		{				DelayUs(1);				cnt++;		}		if(cnt>=240)return 1; // error 		return 0;}/* The functionality :  To write a byte, first learn how to write a bit .*/void DS18B20_WriteByte(u8 cmd){		u8 i;		DS18B20_OUTPUT_MODE(); // Initialize to output mode 		for(i=0;i<8;i++)	  {				DS18B20_OUT=0;  // Generate write time gap ( Write the beginning )				DelayUs(2);				DS18B20_OUT=cmd&0x01; // Send actual data bits 				DelayUs(60);    // Wait for write to complete 				DS18B20_OUT=1;  // Release the bus , Prepare for the next send 				cmd>>=1;        // Continue to send next data 		}}/* The functionality :  To read a byte, first learn how to read a bit .*/u8 DS18B20_ReadByte(void){	 u8 i,data=0;		 for(i=0;i<8;i++)	 {			DS18B20_OUTPUT_MODE(); // Initialize to output mode 			DS18B20_OUT=0;  // Generate read time gap ( Read start )			DelayUs(2);			DS18B20_OUT=1;  // Release the bus 			DS18B20_INPUT_MODE(); // Initialize to input mode 			DelayUs(8);    // wait for DS18B20 Data output of 			data>>=1;      // High compensation 0, Default to 0 Subject to 		  if(DS18B20_IN) data|=0x80;			DelayUs(60);			DS18B20_OUT=1;  // Release the bus , Wait to read the next data 	 }	 return data;}/* The functionality :  Read once DS18B20 Temperature data of   return   value :  Read the temperature data to consider the situation :  There is only one connected to the bus DS18B20 The situation of */u16 DS18B20_ReadTemp(void){	  u16 temp=0;		u8 temp_H,temp_L;	  DS18B20_CheckDevice();   // Send reset pulse 、 Detect the presence of pulses 		DS18B20_WriteByte(0xCC); // skip ROM Sequence detection 		DS18B20_WriteByte(0x44); // Start a temperature conversion 				// Wait for the temperature conversion to complete 		while(DS18B20_ReadByte()!=0xFF){}				DS18B20_CheckDevice();   // Send reset pulse 、 Detect the presence of pulses 		DS18B20_WriteByte(0xCC); // skip ROM Sequence detection 		DS18B20_WriteByte(0xBE); // Reading temperature 				temp_L=DS18B20_ReadByte(); // Read the low temperature data 		temp_H=DS18B20_ReadByte(); // Read high temperature data 		temp=temp_L|(temp_H<<8);   // Synthesis temperature 		return temp;}

3.2 DS18B20.h

#ifndef DS18B20_H#define DS18B20_H#include "stm32f10x.h"#include "sys.h"#include "delay.h"#include "ds18b20.h"#include "usart.h"/* Encapsulation interface */// initialization DS18B20 Is the input mode #define DS18B20_INPUT_MODE() {GPIOB->CRH&=0x0FFFFFFF;GPIOB->CRH|=0x80000000;}// initialization DS18B20 For output mode #define DS18B20_OUTPUT_MODE(){GPIOB->CRH&=0x0FFFFFFF;GPIOB->CRH|=0x30000000;}//DS18B20 IO output #define DS18B20_OUT PBout(15)//DS18B20 IO I want to input #define DS18B20_IN PBin(15) // Function declaration u8 DS18B20_CleckAck(void);u8 DS18B20_CheckDevice(void);void DS18B20_Init(void);u16 DS18B20_ReadTemp(void);u8 DS18B20_ReadByte(void);void DS18B20_WriteByte(u8 cmd);#endif

3.3 The time delay function

/* The functionality :  Time delay us Company */void DelayUs(int us){#ifdef	_SYSTICK_IRQ_	int i,j;	for(i=0;i<us;i++)		for(j=0;j<72;j++);#else	u32 tmp;	SysTick->VAL=0;         //CNT Counter value  	SysTick->LOAD=9*us;     //9 Express 1us	SysTick->CTRL|=1<<0;    // Turn on timer  	do	{			tmp=SysTick->CTRL; // Read status 	}while((!(tmp&1<<16))&&(tmp&1<<0));	SysTick->VAL=0;         //CNT Counter value  	SysTick->CTRL&=~(1<<0); // off timer  #endif	}

3.4 main.c call DS18B20 Read the temperature and print it to the serial port

#include "stm32f10x.h"#include "ds18b20.h"u8 DS18B20_ROM[8]; // Deposit DS18B20 Of 64 by ROM code int main(void){	u16 temp;	USARTx_Init(USART1,72,115200);// A serial port 1 The initialization 	DS18B20_Init();   //DS18B20 initialization 		/*1.  Read DS18B20 Of 64 position ROM code */	// Send reset pulse 、 Detect the presence of pulses 	while(DS18B20_CheckDevice()) 	{			printf("DS18B20 Device does not exist !\n");			DelayMs(500);	}	// Send read 64 by ROM Coded command 	DS18B20_WriteByte(0x33);		// Cyclic reading 64 position ROM code 	for(i=0;i<8;i++)	{			DS18B20_ROM[i]=	DS18B20_ReadByte();			printf("DS18B20_ROM[%d]=0x%X\n",i,DS18B20_ROM[i]);	}		while(1)	{			/*2.  Operate all on the bus at the same time DS18B20 Start to change the temperature */			DS18B20_CheckDevice();   // Send reset pulse 、 Detect the presence of pulses 			DS18B20_WriteByte(0xCC); // skip ROM Sequence detection 			DS18B20_WriteByte(0x44); // Start a temperature conversion ( Let all on the bus DS18B20 Change the temperature )			DelayMs(500);  // Wait for all online DS18B20 Temperature conversion completed 						/*3.  A single targeted read of each DS18B20 Temperature of */			DS18B20_CheckDevice();   // Send reset pulse 、 Detect the presence of pulses 			DS18B20_WriteByte(0x55); // Send matching ROM The order of 			for(i=0;i<8;i++)         // send out 64 Bit code 		    {					DS18B20_WriteByte(DS18B20_ROM[i]); 			}			DS18B20_WriteByte(0xBE);      // Reading temperature 			temp=DS18B20_ReadByte();      // Read the low temperature data 		    temp|=DS18B20_ReadByte()<<8;  // Read high temperature data 			printf("temp1=%d.%d\n",temp>>4,temp&0xF);			printf("temp2=%f\n",temp*0.0625);						DelayMs(500);	}	}
原网站

版权声明
本文为[Hua Weiyun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070921201900.html