Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include "freertos/FreeRTOS.h"
- #include "driver/gpio.h"
- #include "esp_log.h"
- #include "driver/i2c_master.h"
- // Settings
- static const char* TAG = "AirQuality";
- // I2C Variables
- i2c_master_bus_handle_t bus_handle; // this will hold the bus
- i2c_master_dev_handle_t scd40_handle;
- void setup_i2c_bus() {
- i2c_master_bus_config_t i2c_mst_config = {
- .clk_source = I2C_CLK_SRC_DEFAULT,
- .i2c_port = I2C_NUM_1, // tried 0,-1 to no avail
- .scl_io_num = 4,
- .sda_io_num = 3,
- .glitch_ignore_cnt = 7,
- .flags.enable_internal_pullup = true,
- };
- ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle));
- }
- void setup_scd40_device() {
- i2c_device_config_t scd40_dev_cfg = {
- .dev_addr_length = I2C_ADDR_BIT_LEN_7,
- .device_address = 0x62,
- .scl_speed_hz = 100000,
- };
- ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &scd40_dev_cfg, &scd40_handle));
- }
- void start_scd40() {
- uint8_t periodic_measurement_cmd[2] = {0x21, 0xb1};
- ESP_ERROR_CHECK(i2c_master_transmit(scd40_handle, periodic_measurement_cmd, sizeof(periodic_measurement_cmd), -1));
- vTaskDelay(pdMS_TO_TICKS(5000));
- }
- void read_scd40() {
- uint8_t read_measurement_cmd[2] = {0xec, 0x05};
- i2c_master_transmit(scd40_handle, read_measurement_cmd, sizeof(read_measurement_cmd), -1);
- vTaskDelay(pdMS_TO_TICKS(1));
- uint8_t buf[9];
- i2c_master_receive(scd40_handle, buf, sizeof(buf), -1);
- // TODO: buf[2] is the crc of CO2, which should be checked
- uint16_t co2 = (buf[0] << 8) | buf[1];
- // TODO: buf[5] is the crc of TEMP, which should be checked
- uint16_t temp_hex = (buf[3] << 8) | buf[4];
- float temperature = -45.0 + 175.0 * ((float)temp_hex / 65535.0);
- // TODO: buf[5] is the crc of HUM, which should be checked
- uint16_t hum_hex = (buf[6] << 8) | buf[7];
- float humidity = 100.0 * ((float)hum_hex / 65535.0);
- ESP_LOGI("SCD40", "CO2: %u ppm | Temp: %.2f C | Hum: %.2f %%", co2, temperature, humidity);
- }
- void stop_scd40() {
- uint8_t stop_measurement_cmd[2] = {0x3f, 0x86};
- i2c_master_transmit(scd40_handle, stop_measurement_cmd, sizeof(stop_measurement_cmd), -1);
- vTaskDelay(pdMS_TO_TICKS(500));
- ESP_LOGI(TAG, "Stopped SCD40 periodic measurement");
- }
- void app_main(void)
- {
- vTaskDelay(pdMS_TO_TICKS(5000));
- ESP_LOGI(TAG, "Starting...");
- setup_i2c_bus();
- setup_scd40_device();
- start_scd40();
- for (uint8_t i = 0; i < 30; i++) {
- read_scd40();
- vTaskDelay(pdMS_TO_TICKS(5000));
- }
- stop_scd40();
- }
Advertisement
Add Comment
Please, Sign In to add comment