- Подключение к Arduino датчиков DS18B20, DHT22, BMP180

Подключение к Arduino датчиков DS18B20, DHT22, BMP180 с выводом их показаний на LCD 1602 с контроллером HD44780

Практика для студентов. Мясищев А.А.

1. Требуется собрать простой термометр с датчиком DS18B20 и LCD индикатором.

Для этого необходимы:

- Arduino UNO;

- LCD 1602 с контроллером HD44780;

- Датчик температуры DS18B20;

- Программная среда Arduino IDE (здесь используется версия 1.8.4);

- Библиотеки LiquidCrystal, OneWire и DallasTemperature, которые необходимо скачать с Интернета.

На рис.1. представлены некоторые параметры алфавитно-цифрового LCD-модуля MTC16201X фирмы Microtips, который здесь используется.

Рис.1. Алфавитно-цифровой LCD-модуль MTC16201X фирмы Microtips

На рисунке 2 показаны датчик DS18B20 и схема его включения.

Рис.2. Датчик DS18B20 и схема его включения

Основные технические характеристики DS18B20:

Диапазон измерений от –55°C до +125°C;

Точность измерения ±0.5°C в диапазоне от -10°C до +85°C;

Точность измерения: ±2 °C в диапазоне от -55 до 125 °C

Настраиваемое пользователем цифровое разрешение от 9 до 12 бит;

Данные передаются посредством 1-проводного последовательного интерфейса 1-Wire®

Датчик имеет 64-битныйt уникальный серийный номер;

Рабочее напряжение питания от 3.0В до 5.5В;

Время опроса: не более 0.75с.

Ниже представлена таблица подключения LCD и DS18B20 к Arduino UNO:

* Подключение LCD (1602 с контроллером HD44780)

* LCD RS pin to digital pin 12

* LCD Enable pin to digital pin 11

* LCD D4 pin to digital pin 5

* LCD D5 pin to digital pin 4

* LCD D6 pin to digital pin 3

* LCD D7 pin to digital pin 2

* LCD R/W pin to ground

* LCD VSS pin to ground

* LCD VCC pin to 5V

* 10K resistor:

* ends to +5V and ground

* wiper to LCD VO pin (pin 3)

* Датчик температуры DS18B20(вывод DQ) подключен к 8 порту Ардуино

Программа для Ардуино с комментариями:

/* Подключение LCD (1602 с контроллером HD44780)

* LCD RS pin to digital pin 12

* LCD Enable pin to digital pin 11

* LCD D4 pin to digital pin 5

* LCD D5 pin to digital pin 4

* LCD D6 pin to digital pin 3

* LCD D7 pin to digital pin 2

* LCD R/W pin to ground

* LCD VSS pin to ground

* LCD VCC pin to 5V

* 10K resistor:

* ends to +5V and ground

* wiper to LCD VO pin (pin 3)

*

Датчик температуры DS18B20(вывод DQ) подключен к 8 порту Ардуино

*/

#include <OneWire.h>

#include <DallasTemperature.h>

// include the library LCD:

#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin

// with the arduino pin number it is connected to

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

// Data wire is plugged into port 8 on the Arduino

#define ONE_WIRE_BUS 8

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)

OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.

DallasTemperature sensors(&oneWire);

void setup(void)

{

// set up the LCD's number of columns and rows:

lcd.begin(16, 2);

// Start up the library

sensors.begin();

lcd.print(" Temperature:");

}

void loop(void)

{

// call sensors.requestTemperatures() to issue a global temperature

// request to all devices on the bus

sensors.requestTemperatures(); // Send the command to get temperatures

// set the cursor to column 5, line 1

// (note: line 1 is the second row, since counting begins with 0):

lcd.setCursor(5, 1);

// print temperature;

lcd.print(sensors.getTempCByIndex(0));

lcd.print("C");

}

Работающий стенд показан на рисунках 3,4.

Рис.3

Рис.4.

2.Собрать устройство, которое на LCD индикатор выводит температуру вне помещения, в помещении и влажность воздуха в помещении.

Для этого дополним устройство из первой задачи датчиком DHT22 (AM2302), который определяет влажность воздуха и температуру. Датчик DS18B20 из предыдущей задачи будет определять температуру вне помещения, а DHT22 - влажность и температуру внутри помещения.

Для этого необходимы:

- Arduino UNO;

- LCD 1602 с контроллером HD44780;

- Датчик температуры DS18B20;

- Датчик DHT22;

- Программная среда Arduino IDE (здесь используется версия 1.8.4);

- Библиотеки OneWire и DallasTemperature, которые необходимо скачать с Интернета;

- Библиотека DHT с файлом Adafruit_Sensor.h ( https://github.com/adafruit/DHT-sensor-library , https://github.com/adafruit/Adafruit_Sensor ).

Датчик DHT22 подключается к Arduino в соответствии с рисунком 5.

Рис.5. Цоколевка датчика DHT22 и его подключение к 6-му выводу Arduino

Характеристики DHT22:

Влажность: 0-100%

Температура: -40 до +125С

Точность измерения влажности: ± 2%

Точность измерения температуры: ± 0.5С

Питание и I/O 3-5 В

Частота опроса: не более 0.5 Гц (не более 1 раза в 2 сек.)

Размеры: 15.1мм x 25мм x 7.7мм

Программа для Ардуино с комментариями:

/* Подключение LCD (1602 с контроллером HD44780)

* LCD RS pin to digital pin 12

* LCD Enable pin to digital pin 11

* LCD D4 pin to digital pin 5

* LCD D5 pin to digital pin 4

* LCD D6 pin to digital pin 3

* LCD D7 pin to digital pin 2

* LCD R/W pin to ground

* LCD VSS pin to ground

* LCD VCC pin to 5V

* 10K resistor:

* ends to +5V and ground

* wiper to LCD VO pin (pin 3)

*

Датчик температуры DS18B20(вывод DQ) подключен к 8 порту Ардуино

*/

// DHT humidity/temperature sensors:

// Connect pin 1 (on the left) of the sensor to +5V

// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1

// to 3.3V instead of 5V!

// Connect pin 2 of the sensor to whatever your DHTPIN is

// Connect pin 4 (on the right) of the sensor to GROUND

// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

#include <OneWire.h>

#include <DallasTemperature.h>

// include the library LCD:

#include <LiquidCrystal.h>

// include the library DHT humidity/temperature sensors

#include "DHT.h"

// initialize the library by associating any needed LCD interface pin

// with the arduino pin number it is connected to

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

// Data wire is plugged into port 8 on the Arduino

#define ONE_WIRE_BUS 8

#define DHTPIN 6 // 2Pin DHT22 подключен к 6-му выводу Arduino

#define DHTTYPE DHT22 // Выбран датчик DHT 22 (AM2302), AM2321

// Initialize DHT sensor.

DHT dht(DHTPIN, DHTTYPE);

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)

OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.

DallasTemperature sensors(&oneWire);

void setup(void)

{

dht.begin(); // Запуск библиотеки DHT

// set up the LCD's number of columns and rows:

lcd.begin(16, 2);

// Start up the library

sensors.begin();

}

void loop(void)

{

// Wait a few seconds between measurements.

delay(1500);

// call sensors.requestTemperatures() to issue a global temperature

// request to all devices on the bus OneWire

sensors.requestTemperatures(); // Send the command to get temperatures

// Reading temperature (celsius) or humidity(%) with DHT

// Reading temperature or humidity takes about 250 milliseconds!

// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)

float h = dht.readHumidity();

float t = dht.readTemperature();

// print temperature out(DS18B20), temperature in(DHT) and humidity;

//set the cursor to column 0, line 0

lcd.setCursor(0, 0);

lcd.print("To:"); lcd.print(sensors.getTempCByIndex(0)); lcd.print(" ");// DS18B20 - temperature (celsius)

lcd.print("Ti:"); lcd.print(t); //DHT - temperature (celsius)

//set the cursor to column 3, line 1

lcd.setCursor(3, 1);

lcd.print("Hum:"); lcd.print(h); lcd.print("%");//DHT - humidity (%)

}

Работающий стенд показан на рисунке 6.

Рис.6. Фото работающего стенда для определения температур и влажности

3.Собрать устройство, которое на LCD индикатор выводит температуру в помещении, атмосферное давление и высоту над уровнем моря.

Для этого необходимы:

- Arduino UNO;

- LCD 1602 с контроллером HD44780;

- Датчик давления BMP180;

- Программная среда Arduino IDE (здесь используется версия 1.8.4);

- Библиотеки LiquidCrystal, Wire и BMP180_Breakout_Arduino_Library, которые необходимо скачать с Интернета.

Датчик BMP180 подключается к Arduino в соответствии с рисунком 7.

Рис.7. Датчик BMP180 и его подключение к Arduino UNO

Характеристики BMP180:

диапазон измеряемых значений: от 300 гПа до 1100 гПа (от -500м от +9000м над уровнем моря);

напряжение питания: от 3.3 до 5 Вольт;

сила тока: 5 мкА при скорости опроса — 1 Герц;

уровень шума: 0.06 гПа (0.5м) в грубом режиме (ultra low power mode) и 0.02 гПа (0.17м) а режиме максимального разрешения (advanced resolution mode).

С помощью датчика давления возможно примерное определение высоты. На рисунке 8 показана диаграмма изменения давления от высоты и формула для определения высоты. Здесь p — измеренное в данной точке давление, p0 - давление относительно которого идет отсчет высоты. Например, если высота определяется относительно уровня моря, то p0 примерно равно 1013 гПа (1013 мбар). Для летательных аппаратов p0 соответствует уровню взлета.

Рис.8. Диаграмма изменения давления от высоты и формула для определения высоты

В библиотеке SFE_BMP180 уже есть функция, которая использует указанную формулу для получения точной высоты - pressure.altitude(P,p0).

Особенностью библиотеки SFE_BMP180 является то, что процедура получения давления из датчика состоит из нескольких этапов(см. текст программы). В упрощенном виде алгоритм выглядит так:

- запрос у барометра показания встроенного датчика температуры;

- ожидание времени A(переменная status), пока датчик оценивает температуру;

- получение температуры;

- запрос у барометра давление;

- ожидание времени B(переменная status), пока датчик оценивает давление;

- получение значения давления.

Время B зависит от точности измерений, которая задается в функцииstartPressure. Единственный аргумент этой функции может принимать значения от 0 до 3, где 0 — самая грубая и самая быстрая оценка, 3 — самая точная оценка давления.

Программа для Ардуино с комментариями:

/* SFE_BMP180 library example sketch

This sketch shows how to use the SFE_BMP180 library to read the

Bosch BMP180 barometric pressure sensor.

https://www.sparkfun.com/products/11824

Like most pressure sensors, the BMP180 measures absolute pressure.

This is the actual ambient pressure seen by the device, which will

vary with both altitude and weather.

Before taking a pressure reading you must take a temparture reading.

This is done with startTemperature() and getTemperature().

The result is in degrees C.

Once you have a temperature reading, you can take a pressure reading.

This is done with startPressure() and getPressure().

The result is in millibar (mb) aka hectopascals (hPa).

If you'll be monitoring weather patterns, you will probably want to

remove the effects of altitude. This will produce readings that can

be compared to the published pressure readings from other locations.

To do this, use the sealevel() function. You will need to provide

the known altitude at which the pressure was measured.

If you want to measure altitude, you will need to know the pressure

at a baseline altitude. This can be average sealevel pressure, or

a previous pressure reading at your altitude, in which case

subsequent altitude readings will be + or - the initial baseline.

This is done with the altitude() function.

Hardware connections:

- (GND) to GND

+ (Vin) to 5V

You will also need to connect the I2C pins (SCL and SDA) to your

Arduino. The pins are different on different Arduinos:

Any Arduino pins labeled: SDA SCL

Uno, Redboard, Pro: A4 A5

Mega2560, Due: 20 21

Leonardo: 2 3

The SFE_BMP180 library uses floating-point equations developed by the

Weather Station Data Logger project: http://wmrx00.sourceforge.net/

V10 Mike Grusin, SparkFun Electronics 10/24/2013

V1.1.2 Updates for Arduino 1.6.4 5/2015

*/

// Your sketch must #include this library, and the Wire library.

// (Wire is a standard library included with Arduino.):

#include <SFE_BMP180.h>

#include <Wire.h>

#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

// You will need to create an SFE_BMP180 object, here called "pressure":

SFE_BMP180 pressure;

void setup()

{

lcd.begin(16, 2);

// Initialize the sensor (it is important to get calibration values stored on the device).

pressure.begin();

}

void loop()

{

char status;

double T,P,p0=1013.0,a;// 1013.0 - давление в гПа на уровне моря

// You must first get a temperature measurement to perform a pressure reading.

// Start a temperature measurement:

// If request is successful, the number of ms to wait is returned.

// If request is unsuccessful, 0 is returned.

status = pressure.startTemperature();

if (status != 0)

{

// Wait for the measurement to complete:

delay(status);

// Retrieve the completed temperature measurement:

// Note that the measurement is stored in the variable T.

// Function returns 1 if successful, 0 if failure.

status = pressure.getTemperature(T);

if (status != 0)

{

// Print out the measurement:

lcd.setCursor(0, 0);

lcd.print(" Temp=");

lcd.print(T,2);

lcd.print("C");

// Start a pressure measurement:

// The parameter is the oversampling setting, from 0 to 3 (highest res, longest wait).

// If request is successful, the number of ms to wait is returned.

// If request is unsuccessful, 0 is returned.

status = pressure.startPressure(3);

if (status != 0)

{

// Wait for the measurement to complete:

delay(status);

// Retrieve the completed pressure measurement:

// Note that the measurement is stored in the variable P.

// Note also that the function requires the previous temperature measurement (T).

// (If temperature is stable, you can do one temperature measurement for a number of pressure measurements.)

// Function returns 1 if successful, 0 if failure.

status = pressure.getPressure(P,T);

if (status != 0)

{

// Print out the measurement:

lcd.setCursor(0, 1);

lcd.print("P=");

lcd.print(P/1.333,0); // коэф. 1.333 - преобразование гПа в мм.рт.ст.

// If you want to determine your altitude from the pressure reading,

// use the altitude function along with a baseline pressure (sea-level or other).

// Parameters: P = absolute pressure in mb, p0 = 1013 baseline pressure in mb.

// Result: a = altitude in m.

a = pressure.altitude(P,p0);

lcd.print(" H=");

lcd.print(a,2);

lcd.print("m");

}

else lcd.print("error ");

}

else lcd.print("error ");

}

else lcd.print("error ");

}

else lcd.print("error ");

delay(5000); // Pause for 5 seconds.

}

Работающий стенд показан на рисунке 9.

Рис.9. Фото работающего стенда с датчиком давления BMP180

4.Собрать устройство, которое на LCD индикатор выводит температуру внутри помещения(bmp180), температуру вне помещения(DS18B20), атмосферное давление(bmp180) и влажность воздуха(DHT22) .

Это устройство собрано на базе предыдущих путем объединения. правила подключения к выводам Arduino не изменились.

Программа для Ардуино с некоторыми комментариями:

#include <SFE_BMP180.h>

#include <Wire.h>

#include <LiquidCrystal.h>

#include <OneWire.h>

#include <DallasTemperature.h>

#include "DHT.h"

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;

LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#define ONE_WIRE_BUS 8

#define DHTPIN 6 // what digital pin we're connected to

#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321

// Initialize DHT sensor.

DHT dht(DHTPIN, DHTTYPE);

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)

OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.

DallasTemperature sensors(&oneWire);

// You will need to create an SFE_BMP180 object, here called "pressure":

SFE_BMP180 pressure;

void setup()

{

lcd.begin(16, 2);

dht.begin();

sensors.begin();

// Initialize the sensor (it is important to get calibration values stored on the device).

pressure.begin();

}

void loop()

{

char status;

double T,P,p0=1013.0,a;

// call sensors.requestTemperatures() to issue a global temperature

// request to all devices on the bus OneWire

sensors.requestTemperatures(); // Send the command to get temperatures

// Reading temperature (Cel) or humidity(%) with DHT

// Reading temperature or humidity takes about 250 milliseconds!

// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)

float h = dht.readHumidity();

float Tout = sensors.getTempCByIndex(0);

// You must first get a temperature measurement to perform a pressure reading.

// Start a temperature measurement:

// If request is successful, the number of ms to wait is returned.

// If request is unsuccessful, 0 is returned.

status = pressure.startTemperature();

if (status != 0)

{

// Wait for the measurement to complete:

delay(status);

// Retrieve the completed temperature measurement:

// Note that the measurement is stored in the variable T.

// Function returns 1 if successful, 0 if failure.

status = pressure.getTemperature(T);

if (status != 0)

{

// Print out the measurement:

lcd.setCursor(0, 0);

lcd.print("Ti=");

lcd.print(T,1);

lcd.print(" To=");

lcd.print(Tout,1);

lcd.print(" C");

// Start a pressure measurement:

// The parameter is the oversampling setting, from 0 to 3 (highest res, longest wait).

// If request is successful, the number of ms to wait is returned.

// If request is unsuccessful, 0 is returned.

status = pressure.startPressure(3);

if (status != 0)

{

// Wait for the measurement to complete:

delay(status);

// Retrieve the completed pressure measurement:

// Note that the measurement is stored in the variable P.

// Note also that the function requires the previous temperature measurement (T).

// (If temperature is stable, you can do one temperature measurement for a number of pressure measurements.)

// Function returns 1 if successful, 0 if failure.

status = pressure.getPressure(P,T);

if (status != 0)

{

// Print out the measurement bmp180:

lcd.setCursor(0, 1);

lcd.print("P=");

lcd.print(P/1.333,0); // коэф. 1.333 - преобразование гПа в мм.рт.ст.

lcd.print("mm");

//DHT - humidity (%)

lcd.print(" Hum=");

lcd.print(h,0);

lcd.print(" %");

}

else lcd.print("error ");

}

else lcd.print("error ");

}

else lcd.print("error ");

}

else lcd.print("error ");

delay(5000); // Pause for 5 seconds.

}

Работающий стенд показан на рисунке 10.

Рис.10. Фото работающего стенда с датчиками BMP180, DHT22, DS18B20