private static void _sds011_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (e.EventType == SerialData.Chars)
{
// Ignore the in between noise
}
else if (e.EventType == SerialData.WatchChar)
{
SerialDevice serDev = (SerialDevice)sender;
using (DataReader dr = new DataReader(serDev.InputStream))
{
dr.InputStreamOptions = InputStreamOptions.Partial;
uint bytesRead = dr.Load(serDev.BytesToRead);
if (bytesRead > 0)
{
byte[] rawData = new byte[bytesRead];
dr.ReadBytes(rawData);
// If rawData.Length == 10 and rawData[0] = 0xAA and rawData[9] = 0xAB and rawData[1] = 0xC0
// this means we have a valid measure package from the sensor
// and byte[2] = low byte, byte[3] = high byte of uint representing the AQI for PM 2.5
if (rawData.Length >= 10)
{
if ((rawData[0] == 0xAA) && (rawData[1] == 0xC0) && (rawData[9] == 0xAB))
{
// Need to do checksum
byte crc = 0;
for (int i = 0; i < 6; i++)
{
crc += rawData[i + 2];
}
if (crc == rawData[8])
{
// All right, we have a go !!!!
float pm25 = 0, pm10 = 0;
pm25 = (float)((int)rawData[2] | (int)(rawData[3] << 8)) / 10;
pm10 = (float)((int)rawData[4] | (int)(rawData[5] << 8)) / 10;
Console.WriteLine(String.Format("Air quality index: {0}\tPM 10\t{1} µg / m3\tPM 2.5\t{2} µg / m3\tSensor: {3}",
DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'\t'HH':'mm':'ss"),
pm10.ToString("N1"),
pm25.ToString("N1"),
"SDS011"));
}
}
}
}
}
}
}
Comments
Please log in or sign up to comment.