[Diaoye learns programming] Arduino smart agriculture uses MH-Z19B sensor to monitor CO2 concentration and display it on the LCD screen

Insert image description here
Arduino is an open source electronics prototyping platform that allows you to create a variety of interactive projects using simple hardware and software. The core of Arduino is a microcontroller board that can connect various sensors, actuators, displays and other external devices through a series of pins. Arduino programming is based on the C/C++ language. You can use the Arduino IDE (Integrated Development Environment) to write, compile and upload code to the Arduino board. Arduino also has a rich library and community that you can use to extend the functionality of Arduino and learn about Arduino.

The characteristics of Arduino are:
1. Open source: Arduino’s hardware and software are open source, and you can freely modify, copy and share them.
2. Easy to use: Arduino’s hardware and software are designed for beginners and non-professionals, you can easily get started and use them.
3. Cheap: Arduino’s hardware and software are very economical, and you can realize your ideas at a very low cost.
4. Diversity: Arduino has many models and versions. You can choose the appropriate Arduino board according to your needs and preferences.
5. Innovation: Arduino allows you to express your creativity and imagination electronically. You can use Arduino to make a variety of interesting and useful projects, such as robots, smart homes, and art. Devices etc.

Insert image description here
The main features of Arduino smart agriculture:
1. Sensor and actuator integration: Arduino smart agriculture system can integrate various sensors (such as temperature sensor, humidity sensor, soil moisture sensor, etc. ) and actuators (such as water pumps, motors, lights, etc.) to monitor and control the agricultural environment.
2. Data collection and analysis: Arduino smart agricultural system can collect agricultural environment data and conduct real-time analysis and processing. These data can be used to monitor plant growth status, soil conditions, climate changes, etc., and help farmers make appropriate decisions.
3. Remote monitoring and control: The Arduino smart agricultural system can achieve remote monitoring and control through network connection. Farmers can remotely monitor the conditions of farmland through mobile phones, computers and other devices, and perform corresponding control operations, such as remote irrigation, temperature adjustment, etc.
4. Automation and intelligence: Arduino smart agricultural system can automatically perform a series of tasks, such as automatic watering, automatic adjustment of lighting, etc., reducing farmers' labor burden and improving work efficiency. At the same time, through intelligent algorithms and decision-making models, the system can make automated decisions based on real-time data, making agricultural production more intelligent.

The core advantages of Arduino smart agriculture:
1. Low cost: Arduino is an open source hardware platform, the hardware cost is relatively low, and it is easy to obtain and use. Farmers can assemble and customize smart agricultural systems themselves according to their needs and budgets.
2. Flexibility: The Arduino platform has good scalability and compatibility and can be combined with various sensors and actuators to adapt to different agricultural environments and needs. Farmers can choose appropriate components and functions based on their actual conditions.
3. Ease of use: The Arduino platform has simple and easy-to-use programming interfaces and development tools. Even non-professional farmers or beginners can quickly get started and develop. The Arduino community provides a large number of tutorials and sample codes for easy learning and reference.

Limitations of Arduino smart agriculture:
1. Limited processing power: Arduino is a small embedded system with relatively limited processing power. For some complex agricultural applications, more powerful hardware platforms may be needed to handle large amounts of data and complex algorithms.
2. Limited network connection capabilities: Arduino usually communicates through short-distance connections such as wired or Bluetooth. For remote farmland or scenarios that require wide area network connections, additional equipment may be needed to achieve network connections.
3. Lack of standardization and supervision: Since Arduino is an open source platform, it lacks unified standards and supervision mechanisms. This may lead to compatibility issues between different systems and increase the difficulty of system maintenance and management.
4. Requires certain technical knowledge: Although the Arduino platform is relatively easy to use, for some farmers, it still requires certain electronic and programming knowledge. For farmers who lack relevant technical knowledge, additional training and support may be needed.

Insert image description here
It is a common application solution to use the MH-Z19B sensor in Arduino smart agriculture to monitor CO2 concentration and display it on the LCD screen. Below I will explain in detail its main features, application scenarios and matters needing attention from a professional perspective.

main feature:

High-precision measurement: MH-Z19B is a high-precision CO2 sensor that can accurately measure the CO2 concentration in the environment. Its measurement range is usually 0-5000ppm, and the accuracy can reach ±50ppm.

Digital output: The MH-Z19B sensor communicates with Arduino through the serial port and outputs CO2 concentration data in digital form. This makes data reading and processing more convenient.

Programmable control: Through Arduino control, the MH-Z19B sensor can be flexibly configured and controlled. For example, you can set the data update frequency, calibrate sensors, set alarm thresholds, etc.

Low power consumption design: The MH-Z19B sensor adopts a low power consumption design, which is suitable for long-term operation and battery-powered application scenarios.

Application scenarios:

Greenhouse monitoring: In the greenhouse, changes in CO2 concentration have an important impact on plant growth and photosynthesis. The MH-Z19B sensor can be used to monitor the CO2 concentration in the greenhouse in real time, helping farmers adjust ventilation and CO2 supplementation to optimize the plant growth environment.

Indoor air quality monitoring: In indoor air quality monitoring, CO2 concentration is one of the important indicators to evaluate the freshness of the air. By combining the MH-Z19B sensor with Arduino and LCD screen, indoor CO2 concentration can be displayed in real time to remind people of the need for ventilation and air purification.

Environmental monitoring: MH-Z19B sensor can also be used for environmental monitoring applications, such as urban air quality monitoring, industrial area CO2 emission monitoring, etc. By installing the sensors in different locations and using an LCD screen to display the CO2 concentration, CO2 levels in the environment can be monitored and assessed in real time.

Things to note:

Sensor calibration: In order to obtain accurate CO2 concentration data, the MH-Z19B sensor needs to be calibrated. The calibration process includes preheating the sensor, setting calibration points and calibration commands. Before use, please refer to the sensor's technical documentation and follow the correct steps for calibration.

Power supply and connection: MH-Z19B sensor usually requires external power supply, generally using 5V DC power supply. At the same time, the sensor and Arduino communicate through the serial port, and the TX and RX pins of the sensor need to be correctly connected to the corresponding pins of the Arduino.

Data analysis and display: In Arduino, you need to write corresponding code to read the CO2 concentration data output by the sensor and display it on the LCD screen. Pay attention to correctly parsing the serial port data and adapting to the display format of the LCD screen.

Installation location selection: When installing the MH-Z19B sensor, you need to select a suitable installation location to ensure accurate measurement of the CO2 concentration in the environment. Avoid installing the sensor near sources of CO2 or other sources of interference.

Summary:
Using the MH-Z19B sensor to monitor CO2 concentration and display it on the LCD screen is a common application solution in Arduino smart agriculture. Its high precision, digital output and programmable control make it suitable for scenarios such as greenhouse monitoring, indoor air quality monitoring and environmental monitoring. When using it, you need to pay attention to the calibration, power supply and connection of the sensor, data analysis and display, and selection of the appropriate installation location. These considerations will help ensure that the sensor is functioning properly and providing accurate CO2 concentration data.

Insert image description here
Case 1: Basic CO2 concentration monitoring and display

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>

LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C LCD屏幕初始化,地址为0x27,16列2行
SoftwareSerial co2Serial(2, 3); // MH-Z19B传感器串口初始化,引脚2为RX,引脚3为TX

void setup() {
    
    
  lcd.begin(16, 2); // LCD屏幕初始化
  co2Serial.begin(9600); // MH-Z19B传感器串口初始化
}

void loop() {
    
    
  if (co2Serial.available() > 0) {
    
    
    int response = co2Serial.read();
    if (response == 0xFF) {
    
    
      co2Serial.read(); // 读取无用字节
      int co2Concentration = co2Serial.read() << 8; // 读取高位字节
      co2Concentration += co2Serial.read(); // 读取低位字节

      lcd.setCursor(0, 0);
      lcd.print("CO2: ");
      lcd.print(co2Concentration);
      lcd.print(" ppm");
    }
  }
  delay(1000);
}

Interpretation:
Use the LiquidCrystal_I2C library and Wire library to control the LCD screen connected to the I2C bus.
Use the SoftwareSerial library to simulate serial communication and connect the MH-Z19B sensor to digital pins 2 and 3 of the Arduino.
In the setup() function, initialize the serial communication between the LCD screen and the MH-Z19B sensor.
In the loop() function, check whether the MH-Z19B sensor has data available.
Read the data from the sensor and parse the CO2 concentration value.
Use the LCD screen to display the CO2 concentration value.

Case 2: CO2 concentration monitoring and threshold alarm

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);
SoftwareSerial co2Serial(2, 3);

const int threshold = 1000; // CO2浓度阈值

void setup() {
    
    
  lcd.begin(16, 2);
  co2Serial.begin(9600);
}

void loop() {
    
    
  if (co2Serial.available() > 0) {
    
    
    int response = co2Serial.read();
    if (response == 0xFF) {
    
    
      co2Serial.read();
      int co2Concentration = co2Serial.read() << 8;
      co2Concentration += co2Serial.read();

      lcd.setCursor(0, 0);
      lcd.print("CO2: ");
      lcd.print(co2Concentration);
      lcd.print(" ppm");

      if (co2Concentration > threshold) {
    
    
        lcd.setCursor(0, 1);
        lcd.print("High CO2 Level!");
      } else {
    
    
        lcd.setCursor(0, 1);
        lcd.print("                "); // 清空第二行显示
      }
    }
  }
  delay(1000);
}

Interpretation:
In case 2, a CO2 concentration threshold is added for alarm.
defines the threshold of CO2 concentration.
In the loop() function, check whether the MH-Z19B sensor has data available and parse the CO2 concentration value.
Use the LCD screen to display the CO2 concentration value, and determine whether to display high CO2 concentration alarm information based on the threshold value.

Interpretation:

This code uses the LiquidCrystal_I2C library and the Wire library to control the LCD screen connected to the I2C bus.
Use the SoftwareSerial library to simulate serial communication and connect the MH-Z19B sensor to digital pins 2 and 3 of the Arduino.
In the setup() function, initialize the serial communication between the LCD screen and the MH-Z19B sensor.
In the loop() function, check whether the MH-Z19B sensor has data available.
If data is received, read the CO2 concentration value and display it on the LCD screen.
Please note that this example assumes that you have correctly connected the MH-Z19B sensor and LCD screen and installed the required libraries. Make sure you have set up the Arduino development environment correctly and imported the required library files into your project.

Insert image description here
Case 4: Basic CO2 concentration monitoring and display

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>

SoftwareSerial co2Serial(10, 11);  // 设置软串口引脚(RX, TX)
LiquidCrystal_I2C lcd(0x27, 16, 2);  // 设置LCD I2C地址和行列数

void setup() {
    
    
  Serial.begin(9600);  // 与PC串口通信
  co2Serial.begin(9600);  // 与MH-Z19B传感器通信
  lcd.begin(16, 2);  // 初始化LCD
  
  lcd.print("CO2:");  // 显示标签
}

void loop() {
    
    
  if (co2Serial.available()) {
    
    
    // 读取传感器数据
    char response[9];
    co2Serial.readBytes(response, 9);
    
    // 解析CO2浓度值
    int co2 = (response[2] << 8) | response[3];
    
    // 显示CO2浓度值
    lcd.setCursor(4, 0);
    lcd.print("     ");  // 清空原来的数值
    lcd.setCursor(4, 0);
    lcd.print(co2);
    
    // 输出CO2浓度值到串口监视器
    Serial.print("CO2: ");
    Serial.println(co2);
  }
  
  delay(1000);
}

Interpretation of key points:
The program uses the software serial port (SoftwareSerial) to communicate with the MH-Z19B sensor. You need to connect the RX and TX pins of the sensor to Arduino pins 10 and 11 respectively. foot.
To use the LiquidCrystal_I2C library to control the LCD screen of the I2C interface, you need to initialize the LCD in the setup function and set the I2C address and number of rows and columns.
In the loop function, the data returned by the sensor is read through the soft serial port. The data returned by the sensor is a 9-byte array.
When parsing the CO2 concentration value, combine the 3rd and 4th bytes into a 16-bit integer, which is the CO2 concentration value.
Use the lcd.print function to display the CO2 concentration value at the specified position on the LCD screen.
Use the Serial.print function to output the CO2 concentration value to the serial monitor so that the CO2 concentration value can be viewed on the PC.

Program 5: Add CO2 concentration threshold alarm function

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>

SoftwareSerial co2Serial(10, 11);  // 设置软串口引脚(RX, TX)
LiquidCrystal_I2C lcd(0x27, 16, 2);  // 设置LCD I2C地址和行列数

const int co2Threshold = 1000;  // CO2浓度阈值

void setup() {
    
    
  Serial.begin(9600);  // 与PC串口通信
  co2Serial.begin(9600);  // 与MH-Z19B传感器通信
  lcd.begin(16, 2);  // 初始化LCD
  
  lcd.print("CO2:");  // 显示标签
}

void loop() {
    
    
  if (co2Serial.available()) {
    
    
    // 读取传感器数据
    char response[9];
    co2Serial.readBytes(response, 9);
    
    // 解析CO2浓度值
    int co2 = (response[2] << 8) | response[3];
    
    // 显示CO2浓度值
    lcd.setCursor(4, 0);
    lcd.print("     ");  // 清空原来的数值
    lcd.setCursor(4, 0);
    lcd.print(co2);
    
    // 输出CO2浓度值到串口监视器
    Serial.print("CO2: ");
    Serial.println(co2);
    
    // 如果CO2浓度超过阈值,显示警告
    if (co2 > co2Threshold) {
    
    
      lcd.setCursor(0, 1);
      lcd.print("ALERT: High CO2!");
    } else {
    
    
      lcd.setCursor(4, 1);
      lcd.print("                ");  // 清空警告信息
    }
  }
  
  delay(1000);
}

Interpretation of key points:
In the program, a new CO2 concentration threshold constant co2Threshold is added, which is used to set the alarm threshold of CO2 concentration.
After each reading of the CO2 concentration value, check whether the CO2 concentration exceeds the threshold. If the threshold is exceeded, a warning message will be displayed on the second line of the LCD screen.
If the CO2 concentration is lower than the threshold, the warning message on the second line of the LCD screen will be cleared.
In this way, alarm prompts can be issued based on the level of CO2 concentration to help monitors take timely measures.

Program 6: Add CO2 concentration history recording function

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>

SoftwareSerial co2Serial(10, 11);  // 设置软串口引脚(RX, TX)
LiquidCrystal_I2C lcd(0x27, 16, 2);  // 设置LCD I2C地址和行列数

const int co2Threshold = 1000;  // CO2浓度阈值
const int historySize = 10;  // CO2浓度历史记录数组大小
int co2History[historySize];  // CO2浓度历史记录数组
int co2HistoryIndex = 0;  // CO2浓度历史记录数组索引

void setup() {
    
    
  Serial.begin(9600);  // 与PC串口通信
  co2Serial.begin(9600);  // 与MH-Z19B传感器通信
  lcd.begin(16, 2);  // 初始化LCD
  
  lcd.print("CO2:");  // 显示标签
}

void loop() {
    
    
  if (co2Serial.available()) {
    
    
    // 读取传感器数据
    char response[9];
    co2Serial.readBytes(response, 9);
    
    // 解析CO2浓度值
    int co2 = (response[2] << 8) | response[3];
    
    // 将CO2浓度值添加到历史记录数组
    co2History[co2HistoryIndex] = co2;
    co2HistoryIndex = (co2HistoryIndex + 1) % historySize;
    
    // 显示CO2浓度值
    lcd.setCursor(4, 0);
    lcd.print("     ");  // 清空原来的数值
    lcd.setCursor(4, 0);
    lcd.print(co2);
    
    // 输出CO2浓度值到串口监视器
    Serial.print("CO2: ");
    Serial.println(co2);
    
    // 如果CO2浓度超过阈值,显示警告
    if (co2 > co2Threshold) {
    
    
      lcd.setCursor(0, 1);
      lcd.print("ALERT: High CO2!");
    } else {
    
    
      lcd.setCursor(0, 1);
      lcd.print("                ");  // 清空警告信息
    }
    
    // 显示CO2浓度历史记录
    lcd.setCursor(0, 1);
    lcd.print("History:");
    for (int i = 0; i < historySize; i++) {
    
    
      lcd.setCursor(9 + i * 4, 1);
      lcd.print(co2History[(co2HistoryIndex + i) % historySize]);
    }
  }
  
  delay(1000);
}

Interpretation of key points:
In the program, a new CO2 concentration history recording function has been added.
defines an integer array co2History with a size of historySize, which is used to store historical records of CO2 concentration.
The co2HistoryIndex variable is defined as the index of the history record array. Each time the CO2 concentration is updated, the CO2 concentration value is added to the history record array and the index is updated.
Display the history record of CO2 concentration on the second line of the LCD screen, use a for loop to traverse the history record array, and display each CO2 concentration value at the specified position.
This allows you to easily view the historical changes in CO2 concentration and help users understand the trends and change patterns of CO2 concentration.

These three program cases provide some basic functions and extended functions to monitor CO2 concentration and display relevant information on the LCD screen. Here are some key points of these programs: Program 4 is the most basic program, which communicates with the MH-Z19B sensor through the soft serial port, reads the CO2 concentration value returned by the sensor, and displays it on the LCD screen. This program only provides real-time display function of CO2 concentration value. Program 5 adds a CO2 concentration threshold alarm function based on Program 1. It sets a CO2 concentration threshold, and if the real-time measured CO2 concentration exceeds the threshold, a warning message will be displayed on the second line of the LCD screen. This can help users detect when CO2 concentration is too high. Program 6 adds a CO2 concentration history recording function based on program 2. It uses a fixed size array to save the history of CO2 concentration and displays the most recent history on the second line of the LCD screen. This function allows users to observe changing trends and patterns of CO2 concentration. These programs can be modified and expanded based on specific needs. For example, you can modify the CO2 concentration threshold, the size of the history array, or the displayed position according to your needs. You can also add other functions, such as data storage, report generation, etc., to meet the needs of more complex smart agricultural application scenarios. These code examples are for reference only, and the specific implementation may vary depending on factors such as hardware configuration and library version. In actual use, you may need to adjust and optimize according to your specific situation.

Note that the above cases are only for expansion of ideas and are for reference only. They may have errors, be inapplicable, or fail to compile. Your hardware platform, usage scenario, and Arduino version may affect the choice of usage method. When actually programming, you need to make adjustments based on your own hardware configuration, usage scenarios, and specific needs, and conduct multiple actual tests. You'll also want to connect the hardware correctly and understand the specifications and characteristics of the sensors and devices you use. For codes involving hardware operations, you must confirm the correctness and safety of parameters such as pins and levels before use.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_41659040/article/details/134975954