summaryrefslogtreecommitdiff
path: root/main/sprayduck.c
blob: e1ba3aedbeb2bd6c1871b84f219847f7ccee1c3d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "freertos/FreeRTOS.h"
#include "network.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "hal/gpio_types.h"
#include <driver/gpio.h>
#include <stdio.h>
#include "hal/adc_types.h"
#include "esp_adc/adc_oneshot.h"
#include "config.h"

#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);

    char data[4];
    sprintf(data, "%d", value);
    send_packet(data);
    vTaskDelay(1000 / portTICK_PERIOD_MS);

  }
}