Опубликовано 2010-09-20 15:21:28 автором Ruslan

How to work with a temperature sensor DS18B20

In automation devices often need to control any parameter of the environment: temperature , humidity, light , pressure, etc. For this purpose there are sensors - a device that converts a physical quantity to another. To measure the temperature , there is a lot of variety of sensors , from simple contact ( bimetallic , mercury ) to complex temperature sensors in voltage, frequency , current, etc.
Today I will show how digital temperature sensor DS18B20 friends with microcontroller avr atmega8 .

Datchik DS18B20 temperature to avr

  1. GND - minus food .
  2. DQ - line input \ output.
  3. Vdd - plus food .
temperature sensor DS18B20 - with three -pin chip , DS18B20 communicates via 1 -Wire . On the same bus can be sooooo many sensors , this is achieved by the fact that each DS18B20 has a unique code , and thus the microcontroller initializes data with a specific sensor on the bus.
Measured temperature range from -55 ° C to +125 ° C and an accuracy of 0.5 ° C. Resolution default is 12 bits, but may be changed by the user 9 , 10, or 11 bits . Another feature DS18B20 - this is an opportunity to work without an external power supply , it can be powered from the data line ("parasite power"), in the absence of an external source. This ability is realized due to the fact that inside the sensor has a capacitor that is charged via a pullup resistor from a high level on the data line . This method is often referred to as " parasite power ».
Let's put on a simple thermometer DS18B20 and microcontroller atmega8.
Problem :
Digital thermometer should measure temperature and display it on the lcd display .
The scheme is as follows thermometer
Shema thermometer DS18B20

In CodeVision a special library for DS18B20. It contains all necessary functions for working with him. In order to use this sensor in their designs , you must perform a series of simple procedures for connecting the sensor. On the physical level sensor is connected to one terminal of any port . GND pin connected to ground , the output Vdd connected to +5 V and the output DQ line to the selected port. At the same applies to the DQ pin pull-up resistor (typically 4.7 to ), the second terminal of which is connected to +5 V.
The program looks

# include
# include
/ / 1 Wire Bus functions
/ / specify where the sensor is connected
# asm
. equ __ w1_port = 0x18; PORTB
. equ __ w1_bit = 0
# endasm

# include / / library for sensor ds18b20

/ / Alphanumeric LCD Module functions
/ / specify where the screen is connected
# asm
. equ __ lcd_port = 0x12; PORTD
# endasm

# include / / library for LCD
# include / / library, which lives function sprintf

char lcd_buf [ 16] ; / / An array , which generates data for output on lcd
float temperature; / / Variable that will hold the temperature

void main (void)
lcd_init ( 16); / / Initialize LCD 16 characters
w1_init (); / / / / Initialize the tire 1 wire

while ( 1 )
temperature = ds18b20_temperature ( 0); / / get the temperature sensor from 0
sprintf (lcd_buf, "t =% .1 f \ xdfC", temperature); / / String to form the output
lcd_clear (); / / Clear display
lcd_puts (lcd_buf); / / Display the contents of the array to display
lcd_buf delay_ms ( 1000) ; / / Do a delay of 1 second
} ;

Under the program, like everything is clear , only just - it is necessary to specify the properties of the project (s) printf features float and frequency u put on 1 mhz, for this go Project-> Configure-> C Compiler and exhibiting all the screenshot nastroyka DS18B20 Compile and get a thermometer Termometr on DS18B20 As you can see , connect the temperature sensor to u there is no difficulty , 20 minutes and on the lcd thermometer ready .
Now we will take another thermometer but with the conclusion of the temperature on the Led ( seven segment display) . C thermometer on semisegmentnike not so simple as it seems at first glance. The fact that the function ds18b20_temperature of the basic flow blocks until the sensor sends the temperature , which is about one second. Here is the source code of the function

float ds18b20_temperature (unsigned char * addr)
unsigned char resolution;
if (ds18b20_read_spd (addr) == 0 ) return -9999;
resolution = (__ds18b20_scratch_pad.conf_register >> 5) & 3 ;
if (ds18b20_select (addr) == 0 ) return -9999;
w1_write (0x44);
delay_ms (conv_delay [resolution]); here on this delay_ms main thread and stops
if (ds18b20_read_spd (addr) == 0 ) return -9999;
w1_init ();
return (* ((int *) & __ds18b20_scratch_pad.temp_lsb) & ((int) bit_mask [resolution])) * 0.0625;

and we have something to semisegmentnike dynamic display , it means that semisegmentnik will hang for a period of temperature measurement. To solve this problem , we have to manually send commands DS18B20 .
algorithm is :
sent a team to measure the temperature , and more engaged in their own affairs through half seconds
asked sensor measured the temperature whether he , if so, get the data and display them on semisegmentnik . Send commands to the sensor we will be using w1_write . Let's get down to writing code

output values of temperature on the display consists of the following steps :

  1. determines the sign of temperature and reflect it on the display
  2. If the temperature is negative, turn it into a positive .
  3. isolated using bit masks an entire part temperature translate into symbols and reflect on the display. To convert the digitized temperature value in degrees , you need to multiply this value by the weight of the least significant digit . For the whole of the temperature weight LSB (BIT4) Aim is 1 degree , and therefore do not need to multiply .
  4. Select the fractional part , the fractional part to transform the whole , translate into symbols and reflect on the display.

Комментарии - (4)

  • Sanyo.95 говорит:
    Большое спасибо автору за урок, все отлично, но кода для вывода на семисегментник нет, очень хотелось бы взглянуть.
  • Артём говорит:
    День добрый! Можете вот это: "послали команду на измерение температуры, и дальше занимаемся своими делами через полторы секунды спросили у датчика, измерил ли он температуру, если да, то получаем данные и выводим их на семисегментник. Посылать команды датчику мы будем с помощью функции w1_write. Давайте приступим к написанию кода" написать кодом, сам не допираю как всё это будет выглядеть, заранее спасибо!
  • Артём говорит:
    на странице кода не видно/нет...

Добавить комментарий

Для отправки комментария вы должны авторизоваться.