sen0177
is a Rust library/crate that reads air quality data from the
SEN0177 air quality sensor.
embedded_hal
]
traits.Include the following in your Cargo.toml
file:
toml
[dependencies]
sen0177 = "0.4"
If you are in a no_std
environment, you may depend on this crate like so:
toml
[dependencies]
sen0177 = { version = "0.4", default-features = false }
This example shows how to use the sensor when connected to a Linux- based serial device.
Note that this example currently does not work becuase this crate is
tracking the current embedded-hal 1.0.0 alpha, but linux-embedded-hal
is a little behind at the time of writing. If you want to use my patched
version, add the following to your Cargo.toml
:
toml
[patch.crates-io]
linux-embedded-hal = { git = "https://github.com/kelnos/linux-embedded-hal.git", branch = "embedded-hal-1.0.0-alpha.8" }
```rust,norun,ignore use linuxembedded_hal::Serial; use sen0177::{serial::Sen0177, Reading}; use serial::{core::prelude::*, BaudRate, CharSize, FlowControl, Parity, StopBits}; use std::{io, path::Path, time::Duration};
const SERIALPORT: &str = "/dev/ttyS0"; const BAUDRATE: BaudRate = BaudRate::Baud9600; const CHARSIZE: CharSize = CharSize::Bits8; const PARITY: Parity = Parity::ParityNone; const STOPBITS: StopBits = StopBits::Stop1; const FLOW_CONTROL: FlowControl = FlowControl::FlowNone;
pub fn main() -> anyhow::Result<()> { let mut serial = Serial::open(&Path::new(SERIALPORT))?; serial.0.settimeout(Duration::frommillis(1500))?; serial.0.reconfigure(&|settings| { settings.setcharsize(CHARSIZE); settings.setparity(PARITY); settings.setstopbits(STOPBITS); settings.setflowcontrol(FLOWCONTROL); settings.setbaudrate(BAUDRATE) })?; let mut sensor = Sen0177::new(serial);
loop {
match sensor.read() {
Ok(reading) => {
println!("PM1: {}µg/m³, PM2.5: {}µg/m³, PM10: {}µg/m³",
reading.pm1(), reading.pm2_5(), reading.pm10());
},
Err(err) => eprintln!("Error: {:?}", err),
}
}
} ```
Note that the serial device occasionally returns bad data. If you
receive [SensorError::BadMagic
] or [SensorError::ChecksumMismatch
]
from the [AirQualitySensor::read
] call, a second try will usually succeed.
If you're using this with a Raspberry Pi, note that by default the
primary UART is set up as a Linux serial console. You will need
to disable that (by editing /boot/cmdline.txt
) before this will work.
Instead of using a specifiy TTY device node, you should use
/dev/serial0
, which is a symlink to the proper device.
Alternatively, you can use the second UART, but you'll need to load an overlay to assign it to GPIO pins. See UART configuration and the UART-related overlays for more information.