From 005264adc169ca44b1133c122498392c7dbf0ee6 Mon Sep 17 00:00:00 2001 From: "Morgan 'ARR\\!' Allen" Date: Tue, 19 Jul 2022 21:23:40 -0700 Subject: [PATCH] init --- CMakeLists.txt | 5 ++++ README.md | 55 ++++++++++++++++++++++++++++++++++++++++++++ include/esp32-gp2y.h | 21 +++++++++++++++++ main/esp32-gp2y.c | 42 +++++++++++++++++++++++++++++++++ 4 files changed, 123 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 README.md create mode 100644 include/esp32-gp2y.h create mode 100644 main/esp32-gp2y.c diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..a4aa714 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,5 @@ +idf_component_register(SRCS + "main/esp32-gp2y.c" + + INCLUDE_DIRS "include" +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..e12fa23 --- /dev/null +++ b/README.md @@ -0,0 +1,55 @@ +# ESP32 GP2Y Dust Sensor + +## Install + +Designed to be used as an `esp-idf component`. Suggested usage is with `git submodule` + +``` +git submodule add https://git.oit.cloud/morgan/esp32-gp2y.git components/esp32-gp2y/ +git submodule update --init +``` + +## API + +### `typedef gp2y_cfg_t` +`float K` Sensitivity. Default: 0.5 +`float offset_voltage` Voltage level at 0ug/m3 dust. Defaults to 0.6v, dynamically lowers. +`int8_t pin_led` Pin to pulse LED on. +`adc1_channel_t adc_channel` ADC channel to read on. See IDF Guide to get pin to channel reference. +`adc_unit_t adc_unit` ADC unit to read on. + +### `int32_t gp2y_read(gp2y_cfg_t *cfg, uint8_t samples)` +Passing a pointer to `gp2y_cfg_t` and number of samples to take. 100 is a good starting point. + + +## Example +``` +#include +#include +#include "driver/gpio.h" +#include "driver/adc.h" +#include "esp32-gp2y.h" + +#define PIN_LED 5 + +void app_main() { + gp2y_cfg_t gp2y_cfg = GP2Y_DEFAULT_CFG; + gp2y_cfg.adc_channel = channel; + gp2y_cfg.pin_led = PIN_LED; + + gpio_config_t io_conf; + io_conf.intr_type = GPIO_INTR_DISABLE; + io_conf.mode = GPIO_MODE_OUTPUT; + io_conf.pin_bit_mask = (1ULL< +#include + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" + +#include "driver/adc.h" +#include "driver/gpio.h" +#include "esp_log.h" +#include "esp32-gp2y.h" + +int32_t gp2y_read(gp2y_cfg_t *cfg, uint8_t samples) { + int32_t accum = 0; + + for(uint8_t i = 0; i < samples; i++) { + portMUX_TYPE myMutex = portMUX_INITIALIZER_UNLOCKED; + taskENTER_CRITICAL(&myMutex); + + gpio_set_level(cfg->pin_led, 0); + usleep(280); + + accum += adc1_get_raw(cfg->adc_channel); + + gpio_set_level(cfg->pin_led, 1); + + taskEXIT_CRITICAL(&myMutex); + + usleep(9620); + } + + float avg_adc = (accum / samples); + float avg_volt = avg_adc / 4095 * 3.3; + float dV = avg_volt - cfg->offset_voltage; + + // recalibrate offset_volt to lowest value seen + if(dV < 0) { + dV = 0; + cfg->offset_voltage = avg_volt; + } + + return dV / cfg->K * 100.0; +}