Design of intelligent control system for temperature and humidity in vegetable greenhouses based on STM32

I. Introduction

As people's focus on healthy and sustainable lifestyles continues to increase, vegetable greenhouses have become an important part of modern agriculture. Vegetable greenhouses provide a controlled environment that allows farmers to grow vegetables in any season and adjust them as needed. For optimal vegetable growth and yield, precise control of environmental conditions such as temperature and humidity is crucial.

Traditional vegetable greenhouse management usually relies on manual monitoring and adjustment. There are some problems with this method. For example, manual monitoring is prone to errors and delays, and for large-scale vegetable greenhouses, the workload of manual adjustment is huge. Therefore, it has become very important to develop a temperature and humidity management solution for vegetable greenhouses based on an intelligent control system.

The vegetable greenhouse temperature and humidity intelligent control system based on STM32 microcontroller is used to solve the problems of traditional management methods and provide an automated solution. The system utilizes the powerful computing and control capabilities of the STM32 microcontroller, combined with temperature and humidity sensors and actuators, to achieve precise monitoring and control of the vegetable greenhouse environment.

Through this system, farmers can monitor the temperature and humidity in vegetable greenhouses in real time and automatically adjust according to the preset target range. The system can automatically control equipment such as heaters, ventilation equipment and humidifiers in the greenhouse to maintain optimal growing conditions. The goal of the project is to improve the production efficiency and quality of vegetable greenhouses, reduce energy consumption, and reduce labor input. Through the application of intelligent control systems, farmers can achieve more sustainable and efficient agricultural production and provide society with more healthy vegetable products.

image-20230802152046578

2. System design process

2.1 Hardware selection

Hardware selection is an important step in designing an intelligent temperature and humidity control system for vegetable greenhouses.

[1] Main control chip: STM32F103ZET6 The main control chip uses STM32F103ZET6, which is a high-performance ARM Cortex-M3 core microcontroller with rich peripheral resources and powerful processing capabilities. This chip can meet the control and data processing requirements of this project.

[2] Temperature and humidity sensor: DHT11 The DHT11 sensor is used for air temperature and humidity collection. It uses digital signal output, has simplicity, low cost and good accuracy, and is suitable for temperature and humidity monitoring in greenhouse environments.

【3】Soil moisture sensor: Soil moisture sensor uses soil moisture sensor to collect soil moisture data through analog-to-digital converter (ADC) interface. The sensor can accurately measure soil moisture and provide appropriate irrigation water for crops.

[4] Ventilation fan: 5V small fan + relay In order to achieve ventilation control, a 5V small fan is selected as the ventilation device, and its on/off status is controlled through a relay. According to the temperature data and set threshold, the high and low levels of the relay are controlled through the GPIO port of STM32 to realize the start and stop control of the ventilation fan.

【5】Lighting: LED white light module In order to provide appropriate lighting conditions, LED white light module is selected as the lighting device. This module uses the GPIO port of STM32 to control its switch status to turn the light on and off.

[6] Irrigation system: Pumping motor + relay irrigation system uses a pumping motor as the water source, and controls its opening and closing through a relay. The working status of the pumping motor is controlled by the microcontroller controlling the high and low levels of the relay to realize the automated operation of the irrigation system.

【7】Display module: LCD display In order to facilitate the user to observe the current temperature and humidity and other data, the LCD display is used to display the data. Communicate with the LCD display through the digital interface of STM32, and display the collected data on the screen in real time.

2.2 Software design ideas

The code design ideas for this project can be divided into the following key parts:

【1】Initialization settings: First, the initialization settings of the main control chip need to be carried out, including pin configuration, clock settings, etc. At the same time, the LCD display also needs to be initialized and configured for subsequent display of data.

【2】Sensor data collection: Use appropriate library functions or codes to read data from the DHT11 sensor and soil moisture sensor. Communicate with the main control chip through appropriate interfaces to obtain values ​​of temperature, humidity and soil moisture.

【3】Data processing and judgment: Carry out corresponding data processing and judgment based on the collected temperature, humidity and soil moisture values. Determine whether the current temperature exceeds the set range, and whether the soil moisture is lower than the set threshold, etc.

【4】Control actuators: Based on the results of data processing and judgment, control the corresponding actuators, such as ventilation fans, lights and irrigation systems. By setting the corresponding pin level or triggering the relay, the actuator is turned on or off.

【5】LCD display: The collected temperature, humidity and soil moisture values ​​are displayed on the LCD display so that users can monitor them in real time.

【6】User interaction: The user interacts with the system through key input or other methods. Set soil moisture thresholds, adjust temperature ranges, and more.

[7] Loop operation: Organize the above steps into a loop operation program to ensure that the system can continuously collect data, process judgment and control the operation of the actuator.

3. Code implementation

3.1 DHT11 temperature and humidity reading

Read the ambient temperature and humidity of the DHT11 sensor and print it out through the serial port.

#include "stm32f10x.h"
#include "stdio.h"

// 定义DHT11数据引脚
#define DHT11_PIN   GPIO_Pin_0
#define DHT11_PORT  GPIOA

// DHT11初始化函数
void DHT11_Init(void)
{
    
    
    GPIO_InitTypeDef GPIO_InitStructure;

    // 使能GPIOA时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

    // 配置DHT11引脚为推挽输出
    GPIO_InitStructure.GPIO_Pin = DHT11_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(DHT11_PORT, &GPIO_InitStructure);
}

// 延时函数,单位为微秒
void Delay_us(uint32_t nCount)
{
    
    
    uint32_t i;
    for(i=0; i<nCount; i++);
}

// 软件延时函数,单位为毫秒
void Delay_ms(uint32_t nCount)
{
    
    
    uint32_t i;
    for(i=0; i<nCount*1000; i++);
}

// 从DHT11读取一位数据
uint8_t DHT11_ReadBit(void)
{
    
    
    uint8_t retries = 0;
    
    while(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == Bit_RESET)
    {
    
    
        if (retries++ > 100) return 0;
        Delay_us(1);
    }
    
    Delay_us(40);   // 延时40us
    
    if (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == Bit_SET)
        retries = 100;  // 超时标识
    else
        retries = 0;

    while(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == Bit_SET)
    {
    
    
        if (retries++ > 100) return 0;
        Delay_us(1);
    }

    return 1;
}

// 从DHT11读取一个字节数据
uint8_t DHT11_ReadByte(void)
{
    
    
    uint8_t i, temp = 0;
    
    for(i=0; i<8; i++)
    {
    
    
        temp <<= 1;
        temp |= DHT11_ReadBit();
    }
    
    return temp;
}

// 读取DHT11的温湿度值
uint8_t DHT11_ReadData(uint8_t* temperature, uint8_t* humidity)
{
    
    
    uint8_t data[5], checksum;

    // 主机将总线拉低至少18ms
    GPIO_InitTypeDef GPIO_InitStructure;

    GPIO_InitStructure.GPIO_Pin = DHT11_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(DHT11_PORT, &GPIO_InitStructure);

    GPIO_ResetBits(DHT11_PORT, DHT11_PIN);
    Delay_ms(20);
    GPIO_SetBits(DHT11_PORT, DHT11_PIN);
    Delay_us(30);

    // 设置为输入模式
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_Init(DHT11_PORT, &GPIO_InitStructure);
    
    // 等待 DHT11 响应
    if (GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == Bit_RESET)
    {
    
    
        while(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == Bit_RESET);
        while(GPIO_ReadInputDataBit(DHT11_PORT, DHT11_PIN) == Bit_SET);
        
        // 读取5字节数据
        for(uint8_t i=0; i<5; i++)
            data[i] = DHT11_ReadByte();
        
        // 读取校验和
        checksum = DHT11_ReadByte();

        // 校验数据
        if((data[0] + data[1] + data[2] + data[3]) != checksum)
            return 0;
        
        *humidity = data[0];
        *temperature = data[2];

        return 1;
    }
    else
    {
    
    
        return 0;
    }
}

// 初始化USART1
void USART1_Init(void)
{
    
    
    GPIO_InitTypeDef GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;

    // 使能USART1和GPIOA时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);

    // 配置USART1的引脚
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;  // TX
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;  // RX
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    // 配置USART1
    USART_InitStructure.USART_BaudRate = 115200;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Tx;
    USART_Init(USART1, &USART_InitStructure);

    // 使能USART1
    USART_Cmd(USART1, ENABLE);
}

// 发送字符到USART1
void USART1_SendChar(char ch)
{
    
    
    while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
    USART_SendData(USART1, (uint8_t)ch);
}

// 发送字符串到USART1
void USART1_SendString(const char* str)
{
    
    
    while(*str)
    {
    
    
        USART1_SendChar(*str++);
    }
}

int main(void)
{
    
    
    uint8_t temperature, humidity;

    // 初始化DHT11和USART1
    DHT11_Init();
    USART1_Init();

    while(1)
    {
    
    
        if (DHT11_ReadData(&temperature, &humidity))
        {
    
    
            // 发送温湿度数据到串口
            char buffer[50];
            sprintf(buffer, "Temperature: %d°C, Humidity: %d%%\r\n", temperature, humidity);
            USART1_SendString(buffer);
        }

        Delay_ms(2000);  // 2秒钟读取一次数据
    }
}

Download the code to the STM32F103ZET6 development board and connect it to DHT11. When running successfully, the ambient temperature and humidity data will be printed out through the USART1 serial port.

3.2 Read soil moisture value

Collect the humidity value of the soil sensor through channel 1 of ADC1 and print it to the serial port.

#include "stm32f10x.h"
#include "stdio.h"

// 函数声明
void ADC_Configuration(void);
void UART_Configuration(void);
void USART1_SendChar(char ch);

int main(void)
{
    
    
    // 初始化ADC和串口
    ADC_Configuration();
    UART_Configuration();

    while (1)
    {
    
    
        // 启动ADC转换
        ADC_SoftwareStartConvCmd(ADC1, ENABLE);

        // 等待转换完成
        while (!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC));

        // 读取ADC值
        uint16_t adcValue = ADC_GetConversionValue(ADC1);

        // 将ADC值转换为湿度百分比
        float humidity = (float)adcValue / 4095 * 100;

        // 将湿度值打印到串口
        char buffer[20];
        sprintf(buffer, "Humidity: %.2f%%\r\n", humidity);
        for (int i = 0; buffer[i] != '\0'; i++)
        {
    
    
            USART1_SendChar(buffer[i]);
        }

        // 延时一段时间
        for (int i = 0; i < 1000000; i++);
    }
}

// ADC配置
void ADC_Configuration(void)
{
    
    
    ADC_InitTypeDef ADC_InitStructure;
    GPIO_InitTypeDef GPIO_InitStructure;

    // 使能ADC1和GPIOA时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1 | RCC_APB2Periph_GPIOA, ENABLE);

    // 配置GPIOA.1为模拟输入
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    // ADC配置
    ADC_DeInit(ADC1);
    ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
    ADC_InitStructure.ADC_ScanConvMode = DISABLE;
    ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
    ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
    ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
    ADC_InitStructure.ADC_NbrOfChannel = 1;
    ADC_Init(ADC1, &ADC_InitStructure);

    // 配置ADC1的通道1为采样通道
    ADC_RegularChannelConfig(ADC1, ADC_Channel_1, 1, ADC_SampleTime_55Cycles5);

    // 使能ADC1
    ADC_Cmd(ADC1, ENABLE);

    // ADC校准
    ADC_ResetCalibration(ADC1);
    while (ADC_GetResetCalibrationStatus(ADC1));
    ADC_StartCalibration(ADC1);
    while (ADC_GetCalibrationStatus(ADC1));
}

// 串口配置
void UART_Configuration(void)
{
    
    
    GPIO_InitTypeDef GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;

    // 使能USART1和GPIOA时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);

    // 配置USART1引脚
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    // USART配置
    USART_InitStructure.USART_BaudRate = 115200;
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Tx;
    USART_Init(USART1, &USART_InitStructure);

    // 使能USART1
    USART_Cmd(USART1, ENABLE);
}

// 发送字符到USART1
void USART1_SendChar(char ch)
{
    
    
    USART_SendData(USART1, (uint8_t)ch);
    while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}

The above code uses the STM32 standard library functions for configuration and operation. Perform the initial configuration of the ADC in ADC_Configurationthe function, including GPIO pin configuration, ADC clock enable, channel configuration, etc.
Perform the initial configuration of the serial port USART1 in UART_Configurationthe function, including GPIO pin configuration, baud rate setting, etc.

In the main function, enter an infinite loop. In the loop, start the ADC conversion and wait for the conversion to complete.
Read the ADC conversion result through ADC_GetConversionValuethe function and convert it into humidity percentage.
Use sprintfthe function to format the humidity value into a string and use USART1_SendCharthe function to send the string character by character to the USART1 serial port.
Use the delay function to delay for a period of time to control the printing rate.

3.3 Greenhouse fill light control

The following is the code to use STM32F103ZET6 to read the light intensity output by the BH1750 light sensor and control the LED fill light switch according to the threshold:

#include "stm32f10x.h"
#include "i2c.h"
#include "delay.h"

#define BH1750_ADDRESS 0x23

void BH1750_Init()
{
    
    
    // 初始化I2C总线
    I2C_Init();
}

void BH1750_Start()
{
    
    
    // 启动BH1750测量
    uint8_t cmd = 0x01; // 单次高分辨率模式
    I2C_Start();
    I2C_SendByte(BH1750_ADDRESS);
    I2C_WaitAck();
    I2C_SendByte(cmd);
    I2C_WaitAck();
    I2C_Stop();
}

uint16_t BH1750_Read()
{
    
    
    // 读取BH1750测量结果
    uint16_t lux;
    I2C_Start();
    I2C_SendByte(BH1750_ADDRESS + 1); // 发送读命令
    I2C_WaitAck();
    lux = I2C_ReceiveByte() << 8; // 读取高字节
    I2C_Ack();
    lux |= I2C_ReceiveByte(); // 读取低字节
    I2C_NAck();
    I2C_Stop();
    return lux;
}

void LED_Control(uint8_t state)
{
    
    
    // 控制LED照明灯开关
    if (state)
        GPIO_SetBits(GPIOA, GPIO_Pin_8); // 打开LED
    else
        GPIO_ResetBits(GPIOA, GPIO_Pin_8); // 关闭LED
}

int main(void)
{
    
    
    // 初始化GPIO口
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    // 初始化BH1750传感器
    BH1750_Init();

    while (1)
    {
    
    
        // 启动测量
        BH1750_Start();

        // 延时等待测量完成
        DelayMs(200);

        // 读取光照强度
        uint16_t lux = BH1750_Read();

        // 判断阈值并控制LED
        if (lux > 1000)
            LED_Control(1); // 光照强度高于阈值,打开LED
        else
            LED_Control(0); // 光照强度低于阈值,关闭LED
    }
}

The I2C bus and BH1750 sensor are initialized in the code and BH1750_Init()implemented through functions. In the main loop, start the measurement delay and wait for the measurement to be completed. Use BH1750_Read()a function to read the measurement, i.e. light intensity. Determine whether the light intensity is higher than the set value according to the threshold value, and LED_Control()control the switch state of the LED through the function.

4. Summary

This project implements an intelligent temperature and humidity control system for vegetable greenhouses based on STM32 microcontroller. The main control chip of the system uses STM32F103ZET6, which is used to control and coordinate the work of each hardware module. The system includes air temperature and humidity acquisition module (DHT11), soil moisture acquisition module (ADC interface), ventilation fan (5V small fan + relay control), lighting (LED white light module), irrigation system (pumping motor + relay control) and LCD display.

The functions of the system include real-time monitoring of temperature and humidity, soil moisture detection, automatic control of ventilation fans, automatic control of irrigation systems, and data display. Set the soil moisture threshold by pressing the button to realize the automatic watering function. When the soil moisture is lower than the threshold, the system automatically turns on the irrigation system for watering. At the same time, according to the set temperature threshold, the system automatically controls the ventilation fan to cool down.

The vegetable greenhouse temperature and humidity intelligent control system uses STM32 microcontrollers and various sensors to monitor and control environmental parameters, improving the automation and production efficiency of the vegetable greenhouse. At the same time, through automatic control of irrigation and ventilation systems, it can better meet the needs of vegetable growth and improve the yield and quality of crops.

Guess you like

Origin blog.csdn.net/xiaolong1126626497/article/details/133266427