#include "freertos/FreeRTOS.h" #include "network.h" #include "freertos/task.h" #include "esp_log.h" #include "hal/gpio_types.h" #include #include "hal/adc_types.h" #include "esp_adc/adc_oneshot.h" #define THRESHOLD 2000 #define FLIP_GPIO_PIN 23 #define SENSOR_GPIO_PIN 22 #define SENSOR_CHANNEL ADC_CHANNEL_7 #define TAG "sprayduck" /** * @brief Read the value from the soil sensor and return the average over 5 * consectuive readings * * @param[in] handler The adc_oneshot_unit_handle_t handler responsible for * reading the value from the sensor * @return Average of 5 oneshot readings, attuned by ADC_UNIT_1 */ int read_sensor(adc_oneshot_unit_handle_t handler) { int sum = 0; int i = 0; for (i = 0; i < 5; i++) { int value = 0; ESP_ERROR_CHECK(adc_oneshot_read(handler, SENSOR_CHANNEL, &value)); ESP_LOGI(TAG, "ADC%d Channel[%d] Raw Data: %d", ADC_UNIT_1 + 1, SENSOR_CHANNEL, value); sum += value; } return sum / 5; } void app_main(void) { setup_network(); gpio_reset_pin(FLIP_GPIO_PIN); gpio_set_direction(FLIP_GPIO_PIN, GPIO_MODE_OUTPUT); gpio_reset_pin(SENSOR_GPIO_PIN); gpio_set_direction(SENSOR_GPIO_PIN, GPIO_MODE_OUTPUT); adc_oneshot_unit_handle_t handler; adc_oneshot_unit_init_cfg_t adc_config = { .unit_id = ADC_UNIT_1, .ulp_mode = ADC_ULP_MODE_DISABLE, }; ESP_ERROR_CHECK(adc_oneshot_new_unit(&adc_config, &handler)); adc_oneshot_chan_cfg_t channel_config = { .bitwidth = ADC_BITWIDTH_DEFAULT, .atten = ADC_ATTEN_DB_12, }; ESP_ERROR_CHECK(adc_oneshot_config_channel(handler, SENSOR_CHANNEL, &channel_config)); gpio_set_level((gpio_num_t) FLIP_GPIO_PIN, 1); while (1) { //Turn on sensor // gpio_set_level((gpio_num_t) SENSOR_GPIO_PIN, 1); int value = read_sensor(handler); ESP_LOGI("sprayduck", "Checking sensor value average %d", value); if (value > THRESHOLD) { ESP_LOGI("sprayduck", "Pouring water"); gpio_set_level((gpio_num_t) FLIP_GPIO_PIN, 0); } else { ESP_LOGI("sprayduck", "Stopping the water"); gpio_set_level((gpio_num_t) FLIP_GPIO_PIN, 1); } // Turn off Sensor gpio_set_level((gpio_num_t) SENSOR_GPIO_PIN, 0); vTaskDelay(1000 / portTICK_PERIOD_MS); } }