Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
arietis committed Jan 3, 2025
0 parents commit 44f57fe
Show file tree
Hide file tree
Showing 15 changed files with 883 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[build]
target = "riscv32imc-esp-espidf"

[target.riscv32imc-esp-espidf]
linker = "ldproxy"
runner = "espflash flash --monitor" # Select this runner for espflash v3.x.x
rustflags = [ "--cfg", "espidf_time64"] # Extending time_t for ESP IDF 5: https://github.com/esp-rs/rust/issues/110

[unstable]
build-std = ["std", "panic_abort"]

[env]
MCU="esp32c3"
# Note: this variable is not used by the pio builder (`cargo build --features pio`)
ESP_IDF_VERSION = "v5.3.2"
41 changes: 41 additions & 0 deletions .github/workflows/rust_ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
name: Continuous Integration

on:
push:
paths-ignore:
- "**/README.md"
pull_request:
workflow_dispatch:

env:
CARGO_TERM_COLOR: always
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

jobs:
rust-checks:
name: Rust Checks
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
action:
- command: build
args: --release
- command: fmt
args: --all -- --check --color always
- command: clippy
args: --all-targets --all-features --workspace -- -D warnings
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Rust
uses: dtolnay/rust-toolchain@v1
with:
toolchain: nightly
components: rust-src rustfmt clippy
- name: Enable caching
uses: Swatinem/rust-cache@v2
- name: Install ldproxy
run: cargo install ldproxy
- name: Run command
run: cargo ${{ matrix.action.command }} ${{ matrix.action.args }}
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/.vscode
/.embuild
/target
/Cargo.lock
.idea
35 changes: 35 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
[package]
name = "esp32-co2-monitor"
version = "0.1.0"
authors = ["Sergei Guselnikov <[email protected]>"]
edition = "2021"
description = "ESP32-based CO2 monitor using SCD41 sensor and SSD1306 OLED display"
repository = "https://github.com/arietis/esp32-co2-monitor"
license = "MIT"
keywords = ["esp32", "embedded", "co2", "scd41", "oled"]
categories = ["embedded", "hardware-support"]
resolver = "2"
rust-version = "1.77"

[[bin]]
name = "esp32-co2-monitor"
harness = false # do not use the built in cargo test harness -> resolve rust-analyzer errors

[profile.release]
opt-level = "s"

[profile.dev]
debug = true # Symbols are nice and they don't increase the size on Flash
opt-level = "z"

[features]
default = []

experimental = ["esp-idf-svc/experimental"]

[dependencies]
esp-idf-svc = { version = "0.50.0", features = ["critical-section", "embassy-time-driver", "embassy-sync"] }
log = "0.4.22"

[build-dependencies]
embuild = "0.33.0"
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Sergei Guselnikov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
49 changes: 49 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# ESP32 CO2 Monitor

A Rust-based air quality monitoring system using ESP32 microcontroller, SCD41 CO2 sensor, and SSD1306 OLED display.

## Features

- Measures CO2, temperature, and humidity using Sensirion SCD41 sensor
- Displays readings on a SSD1306 OLED display
- Written in Rust using esp-idf framework
- Periodic measurements with configurable interval
- Error handling and display

## Hardware Requirements

- ESP32 development board
- Sensirion SCD41 CO2 sensor
- SSD1306 OLED display (128x64)
- I2C connections:
- SDA: GPIO8
- SCL: GPIO9

## Building and Flashing

1. Install Rust and ESP-IDF toolchain
2. Clone the repository:
```bash
git clone https://github.com/arietis/esp32-co2-monitor.git
cd esp32-co2-monitor
```
3. Build the project:
```bash
cargo build
```
4. Flash to ESP32:
```bash
cargo run
```

## Configuration

The default measurement interval is 5 seconds. You can modify this in `src/main.rs`:

```rust
const MEASUREMENT_INTERVAL_MS: u32 = 5000;
```

## License

This project is licensed under the MIT License - see the LICENSE file for details.
3 changes: 3 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
fn main() {
embuild::espidf::sysenv::output();
}
3 changes: 3 additions & 0 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[toolchain]
channel = "nightly"
components = ["rust-src"]
10 changes: 10 additions & 0 deletions sdkconfig.defaults
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Rust often needs a bit of an extra main task stack size compared to C (the default is 3K)
CONFIG_ESP_MAIN_TASK_STACK_SIZE=8000

# Use this to set FreeRTOS kernel tick frequency to 1000 Hz (100 Hz by default).
# This allows to use 1 ms granularity for thread sleeps (10 ms by default).
#CONFIG_FREERTOS_HZ=1000

# Workaround for https://github.com/espressif/esp-idf/issues/7631
#CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=n
#CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=n
77 changes: 77 additions & 0 deletions src/device.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use crate::display::Ssd1306Display;
use crate::error::AppError;
use crate::sensor::Scd41Sensor;
use esp_idf_svc::hal::i2c::I2cConfig;
use esp_idf_svc::hal::i2c::I2cDriver;
use esp_idf_svc::hal::peripherals::Peripherals;
use esp_idf_svc::hal::prelude::*;
use std::cell::RefCell;
use std::rc::Rc;

/// The device manager interface.
pub struct DeviceManager<'a> {
/// The SSD1306 display.
display: Ssd1306Display<'a>,

/// The SCD-41 sensor.
sensor: Scd41Sensor<'a>,
}

/// The device manager implementation.
impl<'a> DeviceManager<'a> {
/// Create a new device manager.
///
/// # Parameters
/// - `peripherals`: The ESP32 peripherals.
///
/// # Returns
/// The device manager.
pub fn new(peripherals: Peripherals) -> Result<Self, AppError> {
let config = I2cConfig::default().baudrate(100.kHz().into());

let sda = peripherals.pins.gpio8;

let scl = peripherals.pins.gpio9;

let i2c = Rc::new(RefCell::new(
I2cDriver::new(peripherals.i2c0, sda, scl, &config)
.map_err(|e| AppError::I2cError(format!("Failed to initialize I2C: {:?}", e)))?
));

// Initialize display
let mut display = Ssd1306Display::new(Rc::clone(&i2c))?;
display.init()?;
display.clear()?;

// Initialize sensor
let mut sensor = Scd41Sensor::new(Rc::clone(&i2c))?;
sensor.start_periodic_measurement()?;

Ok(Self { display, sensor })
}

/// Update the device manager.
///
/// # Returns
/// The result of the operation.
pub fn update(&mut self) -> Result<(), AppError> {
match self.sensor.read_measurement() {
Ok((co2, temperature, humidity)) => {
log::info!(
"CO2: {} ppm, Temperature: {:.1}°C, Humidity: {:.1}%",
co2, temperature, humidity
);

if let Err(e) = self.display.draw_measurements(co2, temperature, humidity) {
log::error!("Failed to update display: {:?}", e);
}
}
Err(e) => {
log::error!("Failed to read sensor: {:?}", e);
self.display.draw_error("Sensor Error")?;
}
}

Ok(())
}
}
Loading

0 comments on commit 44f57fe

Please sign in to comment.