Подключение I2C датчика температуры и влажности DHT12 к Arduino и вывод данных на LCD1602 HD44780

DHT12 — это улучшенная версия датчика температуры и влажности DHT11 с интерфейсом I2C/TWI. Более подробное описание этого модуля можете найти на странице DHT12 — I2C датчик влажности и температуры. А в этом посте мы подключим по I2C датчик DHT12 к Arduino, установим необходимую библиотеку и будем выводить значения в последовательный порт компьютера и на дисплей LCD1602 используя I2C модуль — PCF8574.

Установка библиотеки DHT12

Для работы с датчиком я использую библиотеку DHT12.zip. Библиотеку можно установить из самой среды следующим образом:

  1. В Arduino IDE открываем менеджер библиотек: Скетч->Подключить библиотеку->Добавить .ZIP библиотеку…Подключение I2C датчика температуры и влажности DHT12 к Arduino - Добавить .ZIP библиотеку...
  2. Выбираем .ZIP архив (DHT12.zip) и кликаем Open/Открыть.Подключение I2C датчика температуры и влажности DHT12 к Arduino - Выбор архива .ZIP
  3. Библиотека установлена.Подключение I2C датчика температуры и влажности DHT12 к Arduino - Библиотека Добавлена.

Ещё можно распаковать архив и добавить в папку «libraries» в папке с Arduino IDE. Не забывайте перезагрузить среду, если на момент добавления Arduino IDE была открыта.

Описание методов библиотеки DHT12.zip

begin(uint8_t, uint8_t)

Инициализация DHT12 на ESP8266

void begin(uint8_t sda, uint8_t scl);

begin()

Инициализация DHT12

void begin();

read()

Читает, преобразовывает и сохраняет данные с DHT12. Возвращает статус DHT12_OK, если всё прошло нормально или DHT12_ERROR_CHECKSUM, DHT12_ERROR_CONNECT, DHT12_MISSING_BYTES в случае ошибки.

int8_t read();

getHumidity()

Возвращает относительную влажность. Данные обновляются при вызове метода read().

float getHumidity();

getTemperature()

Возвращает температуру. Данные обновляются при вызове метода read().

float getTemperature();

 

Схема подключения DHT12 к Arduino

Подключается датчик температуры и влажности DHT12 к Arduino достаточно просто. Схема подключения показана на рисунке.

Схема подключения DHT12 к Arduino Pro MiniНе нужно забывать про подтягивающие резисторы на 10кОм на линии SDA и SCL.

Arduino DHT12
VCC VCC
A4 SDA
GND GND
A5 SCL

Пример скетча

В приведенном ниже скетче мы будем измерять и отсылать данные о состоянии температуры и влажности на компьютер через последовательный порт.

/*
  Добавляем необходимые библиотеки
*/
#include <DHT12.h>
/*
  Создаём экземпляр класса DHT12
*/
DHT12 dht12;

void setup() {
  /*
    Инициализируем DHT12
  */
  dht12.begin();
  Serial.begin(9600);
  delay(2000);
}

void loop() {
  /*
     Читаем данные с DHT12 и получаем статус
  */
  int status = dht12.read();
  switch (status)   {
    case DHT12_OK:
      /*
        Выводим данные в терминал
      */
      Serial.println(F("Status : OK"));
      Serial.print(F("T = "));
      Serial.print(dht12.getTemperature());
      Serial.println(F("*C"));
      Serial.print(F("H = "));
      Serial.print(dht12.getHumidity());
      Serial.println(F(" %"));
      break;
    case DHT12_ERROR_CHECKSUM:
      Serial.print(F("Checksum error"));
      break;
    case DHT12_ERROR_CONNECT:
      Serial.print(F("Connect error"));
      break;
    case DHT12_MISSING_BYTES:
      Serial.print(F("Missing bytes"));
      break;
    default:
      Serial.print(F("Unknown error"));
      break;
  }
  delay(2000);
}

Результат

Открываем монитор порта. В него будут выводиться значения влажности и температуры.

Подключение I2C датчика температуры и влажности DHT12 к Arduino - Результат

Подключение DHT12 к Arduino и вывод на LCD1602

Чтобы сделать устройство автономным, мы будем выводить данные на ЖК дисплей, в моём случае — это LCD1602 (два ряда по 16 символов) который управляется по интерфейсу I2C (PCF8574). Для подключения данного LCD модуля требуется всего 4 линии: питания (Vcc), земля (GND), последовательная линия данных SDA (Serial Data) и последовательная линия тактирования SCL (Serial CLock). Подробнее в статье Подключение LCD1602 к Arduino по I2C (HD44780/PCF8574).

Схема подключения LCD1602 и DHT12 к Arduino

Схема подключения ЖК, DHT12 и Arduino Pro Mini выглядит следующим образом:

Схема подключения I2C PCF8574 LCD1602 и DHT12 к ArduinoВ данном случае можно не использовать дополнительные подтягивающие резисторы, так как они присутствуют на модуле PCF8574.

Пример скетча

В приведенном ниже скетче мы будем измерять и отсылать данные о состоянии температуры и влажности по I2C на ЖК дисплей.

/*
  Добавляем необходимые библиотеки
*/
#include <DHT12.h>
#include <LiquidCrystal_I2C.h>

#define DEGREE (char)0

/*
  Создаём знак градуса
  ..OO.
  .O..O
  .O..O
  ..OO.
  .....
  .....
  .....
*/
uint8_t degree[8] = {
  0b00110,
  0b01001,
  0b01001,
  0b00110,
  0b00000,
  0b00000,
  0b00000
};
/*
  Создаём экземпляр класса DHT12
*/
DHT12 dht12;
/*
  Устанавливаем ЖК-дисплей по адресу 0x27, 16 символов и 2 строки
*/
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  /*
    Инициализируем DHT12
  */
  dht12.begin();
  /*
    Инициализируем ЖК-дисплей
  */
  lcd.init();
  /*
    Включаем подсветку дисплея
  */
  lcd.backlight();
  /*
    Добавляем символ градуса
  */
  lcd.createChar(DEGREE, degree);
}

void loop() {
  /*
     Читаем данные с DHT12 и получаем статус
  */
  int status = dht12.read();
  lcd.clear();
  switch (status) {
    case DHT12_OK:
      /*
        Выводим данные на дисплей
      */
      lcd.setCursor(0, 0);
      lcd.print(F("T = "));
      lcd.print(dht12.getTemperature());
      lcd.print(DEGREE);
      lcd.print(F("C"));

      lcd.setCursor(0, 1);
      lcd.print(F("H = "));
      lcd.print(dht12.getHumidity());
      lcd.print(F(" %"));

      break;
    case DHT12_ERROR_CHECKSUM:
      lcd.setCursor(0, 0);
      lcd.print(F("Checksum error"));
      break;
    case DHT12_ERROR_CONNECT:
      lcd.setCursor(0, 0);
      lcd.print(F("Connect error"));
      break;
    case DHT12_MISSING_BYTES:
      lcd.setCursor(0, 0);
      lcd.print(F("Missing bytes"));
      break;
    default:
      lcd.setCursor(0, 0);
      lcd.print(F("Unknown error"));
      break;
  }
  delay(2000);
}

Результат

Подключение DHT12 к Arduino и вывод на LCD1602 - Результат

Материалы

DHT12 — I2C датчик влажности и температуры
Подключение LCD1602 к Arduino по I2C (HD44780/PCF8574)
LiquidCrystal_I2C

Похожие записи

Комментарии 14

  • Не компилирует данный скетч на подключение к LCD1602 i2c.
    Подскажите в чем дело?
    вот вывод:

    /sdk/hardware/tools/avr/bin/avr-g++ -no-canonical-prefixes -std=gnu++11 -c -g -Os -w -mmcu=atmega328p -DF_CPU=16000000L -DUSB_VID=null -DUSB_PID=null -DARDUINO=10812 -DIDE=»ArduinoDroid» -DARDUINO_ARCH_AVR -DARDUINO_AVR_UNO /build/dht12 I2C (1).cpp -o /build/dht12 I2C (1).cpp.o dht12 I2C (1).ino: In function ‘void loop()’:
    dht12 I2C (1).ino:36:14: error: ‘DHT12_OK’ was not declared in this scope
    dht12 I2C (1).ino:39:17: error: ‘class DHT12’ has no member named ‘getTemperature’
    dht12 I2C (1).ino:45:17: error: ‘class DHT12’ has no member named ‘getHumidity’
    dht12 I2C (1).ino:49:6: error: ‘DHT12_ERROR_CHECKSUM’ was not declared in this scope
    dht12 I2C (1).ino:53:6: error: ‘DHT12_ERROR_CONNECT’ was not declared in this scope
    dht12 I2C (1).ino:57:6: error: ‘DHT12_MISSING_BYTES’ was not declared in this scope
    Return code is not 0

  • Всё получилось, удал л лишние библиотеки и заново установил, всё поехало. Теперь другая проблема, почему при отключении и включении питания, всё показания пропадают и приходится загружать скетч заново?

    • Добавьте небольшую задержку в void setup() , чтобы ЖК дисплей успел настроиться, думается в этом проблема.

  • comprare cialis online 2 mm; Post market surveillance for two to three years, to include reports of explantation, retinal detachment and cataract formation; A minimum endothelial cell count, to be determined by the FDA for various ages;

  • 72 This procedure has the added advantages of rapid recovery and decreased postoperative pain viagra cialis online

  • 49 There is no contraindication for patients considered to be at high risk of breast cancer eg, family history of breast cancer or BRCA1 2 mutation carriers buy cialis online prescription It turned out that she was also a true creator god, and her strength had reached the fourth rank

  • — Download Luckyland Slots Casino mod for android phone apk: Click the download button on the Android device that corresponds to your phone’s operating system at the top of this page! Here EN.VNMOD.NET commit to bring the file download link luckyland-slots-casino-hackmod.apk & full other version, the most accurate from the publisher samanta.irc. Using the Luckyland Slots mod apk file to install it on your android device is a terrific way to enjoy Luckyland on the go. No matter where you are, you can play your way to amazing cash wins with this choice! Read our Luckyland Slots app review to learn more. LuckyLand doesn’t currently have any table games like roulette or blackjack. If you’re looking for a social casino that does have some good table game options, head over to Chumba Casino. You’ll find multiple table games there, which you can play using the same Sweeps Coins model that LuckyLand Slots uses.
    http://keeganmeuj310875.mdkblog.com/14040309/dice-games-played-in-casino
    Version 6.8 for huawei y7 prime We suggest you install the latest version of one of these browsers: Advanced Texas Holdem Poker Chips Pack Fairway Solitaire Governor of Poker Multiplayer  Battle For The Galaxy by am118 — Poker Online! Categories in which Governor Of Poker 2 is included: Medium Texas Holdem Poker Chips Pack Your use of Kongregate’s Services is subject to our revised Cookie Policy, Privacy Policy and Terms of Service. Of course, the most difficult part of translating Texas Hold ’em to the non-meatspace is getting opponent tells onto the screen. Even though you can’t see the faces of people in Governor of Poker 2, players often give clues if they’re bluffing, if they’re frazzled, or if they’re about to be in trouble. You can start to pick up on their personalities after some time, allowing you to call opponents out when you know they have a habit of bluffing. The subtle tells aren’t a huge part of the game, but they’re there, and poker fans will definitely appreciate it.

  • Poniendo en practica todo lo anterior, y destacando que siempre buscan lo mejor para sus usuarios, 888 presenta las mejores tragamonedas del mercado. Entre las que se destacan las siguientes: ¿Cómo hacer apuestas en Casino Tropez gratis en español? El enlace caducará dentro de 72 horas. A continuación, puedes ver cuáles son los cinco mejores juegos de casino gratis en español de este mes. Nuestros expertos en casinos online han evaluado numerosos juegos de casino y máquinas tragamonedas para traerte los favoritos de abril. La oferta de tragamonedas en 888casino es una que remarca la variedad y la calidad con la que el portal trata de imprimir a todo su catálogo para ofrecer algo interesante y divertido a los usuarios tanto novatos como expertos en este terreno. Este casino online cuenta con un buen repertorio que reúne un nivel bastante elevado y que da la mano a un abanico de opciones lo suficientemente grande como para ofrecer algo interesante a cualquier tipo de jugador.
    https://rafaelujvl892212.bloginder.com/24100439/poker-for-dummies-australian-1
    Esta tragaperras online de vídeo está inspirada en la simbología egipcia. Toma como referencia central al ojo de Horus el cual tiene facultades mágicas, de protección, purificación y sanación. Parece que no se ha encontrado nada en esta ubicación. ¿Quizá podrías intentar una búsqueda o usar uno de los enlaces que se muestran a continuación? Así que no es de extrañar que casi todos los desarrolladores de juegos de tragamonedas ahora tengan uno o más tragamonedas con este tema en su rango. Merkur, el proveedor alemán del Grupo Gauselmann, no es una excepción. Si bien Eye of Horus originalmente solo se comercializaba en línea bajo el sol de Merkur, hoy en día también se puede encontrar con los nombres de otros fabricantes que forman parte del Grupo Gauselmann. En Internet.

  • Our tipsters recall the gorgeous scenery and off-the-beaten-track towns on rail journeys from the Arctic Circle to the Peloponnese.Scroll down to see the winning tip and enter the competition to win a Coolstays break Our tipsters recall the gorgeous scenery and off-the-beaten-track towns on rail journeys from the Arctic Circle to the Peloponnese.Scroll down to see the winning tip and enter the competition to win a Coolstays break We’re obviously huge fans of travelling by plane here at TPG, but sleeper train travel can often feel altogether more adventurous, relaxing, romantic and, dare we say, luxurious. Especially if you splurge on that fancy overnight sleeper cabin or berth. Search our journeys To find a sleeper service, select your journey and time in our Journey Planner and, if available, sleeper fare information will be shown. You can also find timetable information on The Caledonian Sleeper website or Great Western Railway’s Night Riviera Sleeper website.
    https://spark-wiki.win/index.php?title=Best_places_to_visit_with_gf_near_me
    A. 12 buses currently run from Patna to Nawada route when booking through ixigo. The various types of buses run by BSRTC Operated By VIP Travels are: The various types of buses run by BSRTC Operated By VIP Travels are: Bihar state road transport corporation (bsrtc) presently has a number of buses operating in the country. It is currently offering its services in various Indian states. Bihar state road transport corporation (bsrtc) also provide night buses. By booking your bus tickets, you can get the services of Bihar state road transport corporation (bsrtc). Below, you can find the different kinds of buses offered by the Bihar state road transport corporation (bsrtc): A BSRTC bus typically runs between the states of Bihar and Jharkhand. A BSRTC bus booking can be quickly made on the redBus app, which provides hassle-free bus ticketing services. Some of the most popular routes covered by a BSRTC bus are mentioned below:

  • Both teams finished 6-10 after the 49ers started 0-9 and the Raiders started 2-0. A coin flip will determine which team gets the No. 9 pick in the 2018 NFL Draft. Still, I expect the Raiders to come out hot and force a win in Carolina. It will be ugly, but they’ll get it done… Just barely. With Coronavirus messing up team practices until recently, Teddy Bridgewater won’t have the same amount of time on the field with his new teammates to find a rhythm in the new system. He’ll still be working the kinks outcome the first Weeks of football. That said, this Carolina team could surprise us once Teddy makes the adjustment and end up being a solid team in the South. Design and development by Jay Boice. Statistical model by Nate Silver, Jay Boice and Neil Paine.
    https://wiki-cafe.win/index.php?title=Best_app_for_betting_sports
    Note that these simulations use a different (simpler) equation to pick games than the picks against the spread. The Kansas City Chiefs and Buffalo Bills open as the two early favorites to win Super Bowl LVII, according to PointsBet. Below you will find the best spread odds for the team’s next game plus Super Bowl and AFC Championship odds and select player props. Click on any odds to claim the posted bonus offer, register a new account and start getting your Browns bets in. Let's dive into the updated Super Bowl odds at FOX Bet. Do you think the Cleveland Browns will make the playoffs? As of August 1, they have -110 odds to make or miss the playoffs at DraftKings Sportsbook, and you can register for an account and receive a $1,000 deposit bonus to wager on either side before the season begins September 8.

  • Wenn Sie Book of Ra online um echtes Geld spielen, sollten Sie jedoch einige Dinge beachten. Zuerst einmal sollten Sie stets verantwortungsbewusst Book of Ra spielen und niemals zu viel Geld auf einmal einsetzen. Wenn Sie einen zu hohen Prozentsatz Ihres Guthabens in zu kurzer Zeit verlieren, wird das nämlich garantiert Auswirkungen auf Ihre Stimmung haben, was dann zu noch höheren Verlusten führen kann. Automaten mit 3 Reels waren vor allem in den Anfangsjahren der Spielautomaten weit verbreitet. Ein Merkmal von 3 Reels Slot sind die wenigen Gewinnlinien, die meistens zwischen 1-5 liegt. Zwar gibt es auch Spielautomaten dieser Kategorie mit mehr Gewinnlinien, diese sind aber seltener vertreten. Vor allem das Früchte Thema wird oft für diese Slots benutzt. Spielautomaten mit 3 Reels sind oftmals eher simpel gestaltet. Freispielfunktionen sind bei manchen Slots eingebaut, sowie eine Multiplikatoren Funktion ist oftmals vorhanden. Fans von Retro Spielautomaten kann man nur empfehlen, hier einen näheren Blick darauf zu werfen.
    http://misojin.co/bbs/board.php?bo_table=free&wr_id=53860
    Nicht zuletzt aufgrund der aus der aktuellen EuGH-Rechtsprechung abgeleiteten Erforderlichkeit einer wiederkehrenden Überprüfung auch durch die österreichischen Gerichte, die nach Auffassung des bet-at-home AG Konzerns derzeit nicht in gebotenem Umfang stattfindet, ging der bet-at-home AG Konzern bisher von einer positiven Entwicklung der Rechtsprechung, insbesondere bei den Obergerichten in den Rechtsmittelinstanzen, bis Ende des ersten Halbjahres 2022 aus. Boni und Aktionen gehören sicherlich zu den wichtigsten Aspekten bei der Wahl eines Online Casinos. Daher legen wir von GGBet besonders großen Wert darauf, unseren neuen Spielern ein attraktives Angebot zu präsentieren, das ihnen den optimalen Einstieg in das Casino Abenteuer ermöglicht. Wir meinen, dass unser GGBet Casino Bonus unseren neuen Gästen einen optimalen Start bietet, den Sie sicher nicht so schnell in einem Online Casino in Deutschland finden werden.

  • The introduction serves to introduce your subject to the reader and give them enough context to fully understand your work—but keep it brief and interesting for the reader(s). When learning how to write a descriptive essay introduction, remember – the first paragraph of your paper is the part that can make your descriptive essay stand out from the others. A descriptive essay is a type of essay in which a writer describes a specific subject in detail. The writer takes help from vivid language to paint a picture in the reader’s mind by engaging the human senses.  Writing descriptive essays require a writer to gain knowledge, observe the world around them, and develop imaginative skills. Here, writers use their five senses to give the reader a sense of who or what they’re describing. This essay must use vivid and figurative language to help catch the reader’s attention.
    https://papa-wiki.win/index.php?title=Can_write
    The language of a compare and contrast thesis usually begins with a conditional word, like «although» or «whereas,» then expresses the outcome of the comparison. For example, «Although the advantages of on-site college courses benefit students living on campus, online courses provide returning adult learners with more flexibility and cost savings.» Here, the two groups affected by the comparison are more clearly identified and connected to the value judgement made by the comparison. Go to Kibin Thesis Statement Generator When selecting a topic, you should consider subjects that are relevant to the content of the course you are taking. Besides, you should consider the length of your compare and contrast essay in criminal justice. Make sure that your topic is broad enough for the required word count and that you will be able to find enough information for your paper. It’s better to choose subjects that have unexpected or unusual differences and similarities.

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

Ваш e-mail не будет опубликован. Обязательные поля помечены *