Технология на температурен сензор

Дизайн на цифров температурен сензор DS18B20 за STM32

DS18B20 Комплект сонда от неръждаема стомана за измерване на температура

DS18B20 е цифров температурен сензор, който използва синхронизиране на една шина, за да комуникира с хоста. само 1 Необходим е проводник, за да завършите отчитането на температурните данни;

DS18B20 има вграден 64-битов сериен номер на продукта за лесна идентификация. Могат да бъдат свързани множество сензори DS18B20 1 Тел, и чрез 64-битово удостоверяване на самоличността, информацията за температурата, събрана от различни сензори, може да се чете отделно.

DS18B20 Комплект сонда от неръждаема стомана за измерване на температура

DS18B20 Комплект сонда от неръждаема стомана за измерване на температура

DS18B20 сонда за температурен сензор TPE Комплект за формоване

DS18B20 сонда за температурен сензор TPE Комплект за формоване

1 проводник DS18B20 температурен датчик

1 проводник DS18B20 температурен датчик

Въведение в DS18B20
2.1 Основни характеристики на DS18B20
1. Напълно цифрово преобразуване и изход на температурата.
2. Усъвършенствана комуникация на данни с една шина.
3. До 12-битова резолюция, с точност до ±0,5 градуса по Целзий.
4. Максималният работен цикъл при 12-битова резолюция е 750 милисекунди.
5. Може да се избере паразитен режим на работа.
6. Температурният диапазон на откриване е –55°C ~+125°C (–67°F ~+257°F).
7. Вграден EEPROM, алармена функция за ограничаване на температурата.
8. 64-битова фотолитография ROM, вграден сериен номер на продукта, удобен за свързване на няколко машини.
9. Различни форми на опаковане, адаптиране към различни хардуерни системи.

Структура на пакета на чип DS18B20

Структура на пакета на чип DS18B20

2.2 DS18B20 пин функция
GND напрежение земя;
DQ единична шина за данни;
VDD захранващо напрежение;
NC празен щифт;

Структурна схема на RAM и EEPROM чип DS18B20

Структурна схема на RAM и EEPROM чип DS18B20

2.3 Принцип на работа и приложение на DS18B20
Откриването на температурата DS18B20 и цифровият изход на данни са напълно интегрирани в един чип, така че има по-силна способност против смущения. Неговият един работен цикъл може да бъде разделен на две части, а именно откриване на температура и обработка на данни.

18B20 има три форми на ресурси на паметта. Те са: ROM памет само за четене, използва се за съхраняване на DS18B20ID код; първият 8 битовете са едноредов сериен код (Кодът DS18B20 е 19H), следното 48 битовете са уникалният сериен номер на чипа; последният 8 битовете са CRC кодът (проверка за излишък) от горните 56 битове. Данните са зададени при производството и не могат да бъдат променяни от потребителя. DS18B20 има общо 64 битове ROM.

RAM регистър на данни, използвани за вътрешни изчисления и достъп до данни, данните се губят след спиране на захранването, DS18B20 има общо 9 байтове RAM, всеки байт е 8 битове. Първият и вторият байт са информацията за стойността на данните след преобразуване на температурата; третият и четвъртият байт са огледален образ на EEPROM на потребителя (обикновено се използва за съхранение на стойност на алармата за температура). Стойността му ще се обнови при нулиране на захранването. Петият байт е огледален образ на третата EEPROM на потребителя. 6-тото, 7th, и 8-ми байтове са регистри за броене, които са предназначени да позволят на потребителите да получат по-висока температурна разделителна способност. Те също така са единици за временно съхранение за вътрешно преобразуване и изчисляване на температурата. 9-ият байт е CRC кодът на първия 8 байтове. EEPROM е енергонезависима памет, използвана за съхраняване на данни, които трябва да бъдат запазени за дълго време, алармени стойности за горна и долна температура, и данни за проверка. DS18B20 има общо 3 битове от EEPROM, и има огледални изображения в RAM за улесняване на работата на потребителя.

DS18B20 работи в режим на 12-битова резолюция по подразбиране. 12-битовите данни, получени след преобразуването, се съхраняват в две 8-битови RAM на DS18B20 (първите два байта). Първият 5 битовете в двоичната система са знакови битове. Ако измерената температура е по-висока от 0, тези 5 бита са 0. Просто умножете измерената стойност по 0.0625 за да получите действителната температура. Ако температурата е по-ниска от 0, тези 5 бита са 1. Измерената стойност трябва да се обърне, добавен от 1, и след това умножено по 0.0625 за да получите действителната температура. Или използвайте битова операция за извличане на температура: десетичните знаци заемат долната 4 битове, а горните битове са цели числа (отрицателните числа не се вземат предвид).

2.4 Таблица с инструкции за ROM чип DS18B20
1. Прочетете ROM [33З] (шестнадесетичната командна дума е в квадратни скоби).
Тази команда позволява на контролера на шината да чете 64-битовия ROM на DS18B20. Тази инструкция може да се използва само когато има само един DS18B20 в шината. Ако са свързани повече от един, ще възникнат конфликти на данни по време на комуникация.

2. atch ROM [55З]
Тази инструкция е последвана от 64-битов сериен номер, издаден от контролера. Когато има няколко DS18B20 в шината, може да отговори само чипът със същия сериен номер като този, издаден от контролера, и другите чипове ще изчакат следващото нулиране. Тази инструкция е подходяща за свързване с един чип и много чипове.

3. Пропуснете ROM [CCH]
Тази инструкция кара чипа да не реагира на ROM кода. В случай на един автобус, тази инструкция може да се използва за спестяване на време. Ако тази инструкция се използва, когато са свързани множество чипове, ще възникнат конфликти на данни, което води до грешки.

4. Търсене в ROM [F0H]
След инициализиране на чипа, инструкцията за търсене позволява 64-битовата ROM на всички устройства да бъде идентифицирана чрез елиминиране, когато множество чипове са свързани към шината.

5. Търсене на аларма [ВСЯКА]
In the case of multiple chips, the alarm chip search instruction only responds to chips that meet the alarm condition of temperature higher than TH or less than TL. As long as the chip is not powered off, the alarm state will be maintained until the temperature is measured again and the alarm condition is not reached.

6. Write Scratchpad [4EH]
This is the instruction to write data to RAM. The two bytes of data written subsequently will be stored at address 2 (TH of alarm RAM) and address 3 (TL of alarm RAM). The write process can be terminated by a reset signal.

7. Read Scratchpad (read data from RAM) [BEH]
This instruction will read data from RAM, starting from address 0 and up to address 9, completing the reading of the entire RAM data. The chip allows the reset signal to terminate the reading process, това е, the subsequent unnecessary bytes can be ignored to reduce the reading time.

8. Copy Scratchpad (copy RAM data to EEPROM) [48З]
This instruction stores the data in RAM into EEPROM so that the data will not be lost when power is off. Since the chip is busy with EEPROM storage processing, when the controller sends a read time slot, the bus outputs “0”, and when the storage work is completed, the bus will output “1”.
In parasitic working mode, a strong pull-up must be used immediately after this instruction is issued and maintained for at least 10MS to maintain chip operation.

9. Convert T (temperature conversion) [44З]
After receiving this instruction, the chip will perform a temperature conversion and store the converted temperature value in the 1st and 2nd addresses of RAM. Since the chip is busy with temperature conversion processing, when the controller sends a read time slot, the bus outputs “0”, and when the storage work is completed, the bus will output “1”. In parasitic working mode, a strong pull-up must be used immediately after this instruction is issued and maintained for at least 500MS to maintain chip operation.

10. Recall EEPROM (Copy the alarm value in EEPROM to RAM) [B8H]
This instruction copies the alarm value in EEPROM to the 3rd and 4th bytes in RAM. Since the chip is busy with copying processing, when the controller sends a read time slot, the bus outputs “0”, and when the storage work is completed, the bus outputs “1”. Освен това, this instruction will be automatically executed when the chip is powered on and reset. По този начин, the two alarm byte bits in RAM will always be the mirror image of the data in EEPROM.

11. Read Power Supply (Working Mode Switch) [B4H]
After this instruction is issued, a read time gap is issued, and the chip will return its power status word. “0” is the parasitic power state and “1” is the external power state.

2.5 DS18B20 Timing Diagram
2.5.1 DS18B20 Reset and Response Relationship Diagram
A reset must be performed before each communication. The reset time, waiting time, and response time should be strictly programmed according to the timing.
DS18B20 read and write time gap: DS18B20 data reading and writing is confirmed by the time gap processing bit and command word to exchange information.

DS18B20 reset and response relationship diagram

DS18B20 reset and response relationship diagram

2.5.2 Write data 0 and data 1 to DS18B20
In the first 15uS of the write data time gap, the bus needs to be pulled low by the controller, and then it will be the chip sampling time for the bus data. The sampling time is 15~60uS. If the controller pulls the bus high during the sampling time, it means writing “1”, and if the controller pulls the bus low, it means writing “0”.
Each bit of transmission should have a low-level start bit of at least 15uS, and the subsequent data “0” или “1” should be completed within 45uS.
The transmission time of the entire bit should be kept at 60~120uS, otherwise the normal communication cannot be guaranteed.
Забележка: DS18B20 reads and writes data from the low bit.

Write data 0 and data 1 to DS18B20

Write data 0 and data 1 to DS18B20

2.5.3 Reading data 0 and data 1 from DS18B20
The sampling time of the control during the read time gap should be more accurate. During the read time gap, the host must also generate a low level of at least 1uS to indicate the start of the read time. Тогава, in 15uS after the bus is released, the DS18B20 will send the internal data bit. По това време, if the control finds that the bus is high, it means reading “1”, and if the bus is low, it means reading data “0”. Before reading each bit, the controller adds a start signal.

Read data 0 and data 1 from DS18B20

Read data 0 and data 1 from DS18B20

Забележка: The data bit must be read within 15uS of the start of the read gap to ensure correct communication.

During communication, 8 bits of “0” или “1” are used as a byte, and the reading or writing of the byte starts from the low bit.

2.5.4 Order of reading temperature once (only a single DS18B20 on the bus)

1. Send reset signal
2. Detect response signal
3. Send 0xCC
4. Send 0x44
5. Send reset signal
6. Detect response signal
7. Write 0xcc
8. Write 0xbe
9. Loop 8 times to read the low byte of temperature
10. Loop 8 times to read the high byte of temperature
11. Synthesize 16-bit temperature data and process

3. Driver code

3.1 DS18B20.c
#includeds18b20.h
/*
функция: DS18B20 initialization
Hardware connection: PB15
*/
void DS18B20_Init(void)
{
RCC->APB2ENR|=1<<3; //PB
GPIOB->CRH&=0x0FFFFFFF;
GPIOB->CRH|=0x30000000;
GPIOB->ODR|=1<<15; //Pull-up
}

/*
функция: Check if the DS18B20 device exists
Return value: 1 means the device does not exist 0 means the device is normal
*/
u8 DS18B20_CheckDevice(void) //Contains reset pulse, detection pulse
{
DS18B20_OUTPUT_MODE();//Initialize to output mode
DS18B20_OUT=0; //Generate reset pulse
DelayUs(750); //Generate 750us low level
DS18B20_OUT=1; //Release bus
DelayUs(15); //Wait for DS18B20 response
ако(DS18B20_CleckAck())//Detect existence pulse
{
return 1;
}
return 0;
}

/*
функция: Detect existence pulse of DS18B20 device
Return value: 1 indicates error 0 indicates normal
*/
u8 DS18B20_CleckAck(void)
{
u8 cnt=0;
DS18B20_INPUT_MODE();//Initialize to input mode
докато(DS18B20_IN&&cnt<200) //Wait for DS18B20 response existence pulse
{
DelayUs(1);
cnt++;
}
ако(cnt>=200)return 1; //грешка

cnt=0;
докато((!DS18B20_IN)&&cnt<240) //wait for DS18B20 to release the bus
{
DelayUs(1);
cnt++;
}
ако(cnt>=240)return 1; //грешка
return 0;
}

/*
функция: Write a byte
First learn how to write a bit.
*/
void DS18B20_WriteByte(u8 cmd)
{
u8 i;
DS18B20_OUTPUT_MODE(); //Initialize to output mode
за(i=0;i<8;i++)
{
DS18B20_OUT=0; //Generate write time gap (write start)
DelayUs(2);
DS18B20_OUT=cmd&0x01; //Send actual data bit
DelayUs(60); //Wait for write completion
DS18B20_OUT=1; //Release the bus and prepare for the next transmission
cmd>>=1; //Continue to send the next bit of data
}
}

/*
функция: Read a byte
First learn how to read a bit.
*/
u8 DS18B20_ReadByte(void)
{
u8 i,data=0;
за(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 bus
DS18B20_INPUT_MODE(); //Initialize to input mode
DelayUs(8); //Wait for DS18B20 data output
data>>=1; //Fill high bit with 0, default is 0
ако(DS18B20_IN) data|=0x80;
DelayUs(60);
DS18B20_OUT=1; //Release bus, wait for reading next bit of data
}
return data;
}

/*
функция: Read the temperature data of DS18B20 once
Return value: the temperature data read
Considered situation: There is only one DS18B20 connected to the bus
*/
u16 DS18B20_ReadTemp(void)
{
u16 temp=0;
u8 temp_H,temp_L;
DS18B20_CheckDevice(); //Send reset pulse, detect pulse
DS18B20_WriteByte(0xCC); //Skip ROM sequence detection
DS18B20_WriteByte(0x44); //Start a temperature conversion

//Wait for temperature conversion to complete
докато(DS18B20_ReadByte()!=0xFF){}

DS18B20_CheckDevice(); //Send reset pulse, detect pulse
DS18B20_WriteByte(0xCC); //Skip ROM sequence detection
DS18B20_WriteByte(0xBE); //Read temperature

temp_L=DS18B20_ReadByte(); //Read low temperature data
temp_H=DS18B20_ReadByte(); //Read high temperature data
temp=temp_L|(temp_H<<8); //Synthesized temperature
return temp;
}

3.2 DS18B20.h

#ifndef DS18B20_H
#define DS18B20_H
#includestm32f10x.h
#includesys.h
#includedelay.h
#includeds18b20.h
#includeusart.h

/*Package interface*/

//Initialize DS18B20 to input mode
#define DS18B20_INPUT_MODE() {GPIOB->CRH&=0x0FFFFFFF;GPIOB->CRH|=0x80000000;}

//Initialize DS18B20 to output mode
#define DS18B20_OUTPUT_MODE(){GPIOB->CRH&=0x0FFFFFFF;GPIOB->CRH|=0x30000000;}

//DS18B20 IO port output
#define DS18B20_OUT PBout(15)

//DS18B20 IO port 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

poYBAGDYdXCAWkKMAAAAK8RNs4s030.png
3.3 Delay function

/*
функция: Delay in us
*/
void DelayUs(int us)
{
#ifdef _SYSTICK_IRQ_
int i,j;
за(i=0;iVAL=0; //CNT counter value
SysTick->LOAD=9*us; //9 means 1us
SysTick->CTRL|=1<<0; //Start timer
направете
{
tmp=SysTick->CTRL; //Read status
}докато((!(tmp&1<<16))&&(tmp&1<<0));
SysTick->VAL=0; //CNT counter value
SysTick->CTRL&=~(1<<0); //Turn off the timer
#endif
};i++)>

3.4 main.c Call DS18B20 to read the temperature and print it to the serial port

#includestm32f10x.h

#includeds18b20.h

u8 DS18B20_ROM[8]; //Store the 64-bit ROM code of DS18B20

int main(void)
{
u16 temp;
USARTx_Init(USART1,72,115200);//Initialization of serial port 1
DS18B20_Init(); //DS18B20 initialization

/*1. Read the 64-bit ROM code of DS18B20*/
//Send reset pulse, detect existence pulse
докато(DS18B20_CheckDevice())
{
printf(“DS18B20 device does not exist!\n”);
DelayMs(500);
}
//Send the command to read the 64-bit ROM code
DS18B20_WriteByte(0x33);

//Loop read 64-bit ROM code
за(i=0;i<8;i++)
{
DS18B20_ROM[i]= DS18B20_ReadByte();
printf(“DS18B20_ROM[%d]=0x%X\n”,i,DS18B20_ROM[i]);
}

докато(1)
{
/*2. Simultaneously operate all DS18B20 on the bus to start converting temperature*/
DS18B20_CheckDevice(); //Send reset pulse, detect pulse
DS18B20_WriteByte(0xCC); //Skip ROM sequence detection
DS18B20_WriteByte(0x44); //Start a temperature conversion (let all DS18B20 on the bus convert the temperature)
DelayMs(500); //Wait for all DS18B20 temperature conversions on the line to complete

/*3. Single targeted reading of the temperature of each DS18B20*/
DS18B20_CheckDevice(); //Send reset pulse, detect pulse
DS18B20_WriteByte(0x55); //Send command to match ROM
за(i=0;i<8;i++) //Send 64-bit code
{
DS18B20_WriteByte(DS18B20_ROM[i]);
}
DS18B20_WriteByte(0xBE); //Read temperature
temp=DS18B20_ReadByte(); //Read low-order temperature data
Темп|=DS18B20_ReadByte()<<8; //Read high-order temperature data
printf(“temp1=%d.%d\n”,Темп>>4,Темп&0xF);
printf(“temp2=%f\n”,temp*0.0625);

DelayMs(500);
}
}