Estação Meteorológica Avançada v2.0: Monitoramento em Tempo Real de Temperatura, Pressão, Umidade e Altitude
Construa uma estação meteorológica compacta que mede com precisão temperatura, pressão, umidade e altitude direto na sua sala.
História
Usando o Adafruit Starter Pack para Windows 10 IoT Core em um Raspberry Pi 2, este projeto demonstra como interligar um sensor BME280 (ou BMP280) para ler dados ambientais e publicá-los em um serviço na nuvem.
Se você possui um BMP280, siga o guia da Estação Meteorológica v1: Estação Meteorológica v1.
Hardware
Conecte o Raspberry Pi 2 a uma protoboard e ligue o sensor BME280 conforme o diagrama Fritzing na seção "Esquemáticos" abaixo.
Software
Baixe o código inicial de GitHub – ms-iot/adafruitsample. Vamos guiá-lo na adição do código necessário para comunicar com o sensor e publicar suas leituras.
Abra Lesson_203v2\StartSolution\lesson_203v2.sln e edite mainpage.xaml.cs.
Uma versão totalmente completa está disponível em Lesson_203v2\FullSolution\lesson_203v2.sln.
MainPage.xaml.cs
Adicione referência à classe BME280:
public sealed partial class MainPage : Page {
// Cria novo objeto para nossa classe de sensor
BME280 BME280;
Inicialize o sensor em OnNavigatedTo:
// Cria novo objeto para nossa classe de sensor BME280 = new BME280Sensor(); // Inicializa o sensor await BME280.Initialize();
Em seguida, adicione código para coletar e registrar dados:
- Crie variáveis para temperatura, pressão, umidade e altitude, inicializadas com 0.
- Defina uma constante de pressão ao nível do mar (padrão 1013,25 hPa).
- Leia as quatro medições dez vezes e imprima no console de debug.
// Inicialize com 0
float temp = 0;
float pressure = 0;
float altitude = 0;
float humidity = 0;
// Crie constante para pressão ao nível do mar
const float seaLevelPressure = 1022.00f;
// Leia 10 amostras dos dados
for (int i = 0; i < 10; i++) {
temp = await BME280.ReadTemperature();
pressure = await BME280.ReadPreasure();
altitude = await BME280.ReadAltitude(seaLevelPressure);
humidity = await BME280.ReadHumidity();
// Escreva valores no console de debug
Debug.WriteLine("Temperatura: " + temp.ToString() + " °C");
Debug.WriteLine("Umidade: " + humidity.ToString() + " %");
Debug.WriteLine("Pressão: " + pressure.ToString() + " Pa");
Debug.WriteLine("Altitude: " + altitude.ToString() + " m");
Debug.WriteLine("\n");
}
BME280.cs
Abra BME280.cs e adicione o seguinte após o enum de endereços de registradores:
// String para nome amigável do barramento I2C const string I2CControllerName = "I2C1"; // Cria dispositivo I2C private I2cDevice bme280 = null; // Cria novos dados de calibração para o sensor BME280_CalibrationData CalibrationData; // Variável para verificar se dispositivo foi inicializado bool init = false;
Aprimore o método Initialize para configurar a conexão I2C:
public async Task Initialize() {
Debug.WriteLine("BME280::Initialize");
try {
I2cConnectionSettings settings = new I2cConnectionSettings(BME280_Address);
settings.BusSpeed = I2cBusSpeed.FastMode;
string aqs = I2cDevice.GetDeviceSelector(I2CControllerName);
DeviceInformationCollection dis = await DeviceInformation.FindAllAsync(aqs);
bme280 = await I2cDevice.FromIdAsync(dis[0].Id, settings);
if (bme280 == null) {
Debug.WriteLine("Dispositivo não encontrado");
}
} catch (Exception e) {
Debug.WriteLine("Exceção: " + e.Message + "\n" + e.StackTrace);
throw;
}
}
Adicione a rotina Begin para verificar a assinatura do sensor e carregar dados de calibração:
private async Task Begin() {
Debug.WriteLine("BME280::Begin");
byte[] WriteBuffer = new byte[] { (byte)eRegisters.BMP280_REGISTER_CHIPID };
byte[] ReadBuffer = new byte[] { 0xFF };
bmp280.WriteRead(WriteBuffer, ReadBuffer);
Debug.WriteLine("Assinatura BME280: " + ReadBuffer[0].ToString());
if (ReadBuffer[0] != BMP280_Signature) {
Debug.WriteLine("BMP280::Begin Assinatura Incompatível.");
return;
}
init = true;
CalibrationData = await ReadCoefficeints();
await WriteControlRegister();
await WriteControlRegisterHumidity();
}
Helpers de registradores de controle:
private async Task WriteControlRegisterHumidity() {
byte[] WriteBuffer = new byte[] { (byte)eRegisters.BMP280_REGISTER_CONTROLHUMID, 0x03 };
bmp280.Write(WriteBuffer);
await Task.Delay(1);
}
private async Task WriteControlRegister() {
byte[] WriteBuffer = new byte[] { (byte)eRegisters.BMP280_REGISTER_CONTROL, 0x3F };
bmp280.Write(WriteBuffer);
await Task.Delay(1);
}
Funções utilitárias para ler dados de registradores:
private UInt16 ReadUInt16_LittleEndian(byte register) {
UInt16 value = 0;
byte[] writeBuffer = new byte[] { 0x00 };
byte[] readBuffer = new byte[] { 0x00, 0x00 };
writeBuffer[0] = register;
bmp280.WriteRead(writeBuffer, readBuffer);
int h = readBuffer[1] << 8;
int l = readBuffer[0];
value = (UInt16)(h + l);
return value;
}
private byte ReadByte(byte register) {
byte value = 0;
byte[] writeBuffer = new byte[] { 0x00 };
byte[] readBuffer = new byte[] { 0x00 };
writeBuffer[0] = register;
bmp280.WriteRead(writeBuffer, readBuffer);
value = readBuffer[0];
return value;
}
Funções de calibração e compensação são derivadas diretamente do datasheet BMP280 e já fornecidas.
Implemente ReadTemperature para retornar temperatura do sensor em graus Celsius:
public async TaskReadTemperature() { if (!init) await Begin(); byte tmsb = ReadByte((byte)eRegisters.BMP280_REGISTER_TEMPDATA_MSB); byte tlsb = ReadByte((byte)eRegisters.BMP280_REGISTER_TEMPDATA_LSB); byte txlsb = ReadByte((byte)eRegisters.BMP280_REGISTER_TEMPDATA_XLSB); Int32 t = (tmsb << 12) + (tlsb << 4) + (txlsb >> 4); double temp = BMP280_compensate_T_double(t); return (float)temp; }
Complete ReadPreasure (mantendo o typo original para compatibilidade):
public async TaskReadPreasure() { if (!init) await Begin(); if (t_fine == Int32.MinValue) await ReadTemperature(); byte tmsb = ReadByte((byte)eRegisters.BMP280_REGISTER_PRESSUREDATA_MSB); byte tlsb = ReadByte((byte)eRegisters.BMP280_REGISTER_PRESSUREDATA_LSB); byte txlsb = ReadByte((byte)eRegisters.BMP280_REGISTER_PRESSUREDATA_XLSB); Int32 t = (tmsb << 12) + (tlsb << 4) + (txlsb >> 4); Int64 pres = BMP280_compensate_P_Int64(t); return ((float)pres) / 256; }
Finalmente, implemente ReadAltitude para calcular altitude usando a fórmula barométrica:
public async TaskReadAltitude(float seaLevel) { if (!init) await Begin(); float pressure = await ReadPreasure(); pressure /= 100; return 44330.0f * (1.0f - (float)Math.Pow((pressure / seaLevel), 0.1903f)); }
Seu projeto está pronto para deploy!
Saída Esperada
Temperatura: 24,46 °C
Umidade: 54,37 %
Pressão: 99738,73 Pa
Altitude: 205,17 m
Fonte: Estação Meteorológica V 2.0
Processo de manufatura
- Estação Meteorológica Solar DIY com Raspberry Pi
- Construindo Estação Meteorológica Externa com Raspberry Pi 2 e ADS‑WS1
- Construa Estação Meteorológica Raspberry Pi que Envia Dados Diários por Email
- Monitoramento Remoto do Tempo com Raspberry Pi 3 e PubNub
- Integre sua Estação Meteorológica ao CWOP: Guia Prático
- Monitor Meteorológico – Estação Meteorológica DIY com Raspberry Pi e Upload para Dropbox
- Estação Meteorológica Compacta: Arduino Nano e ESP8266 com BMP280 e Display OLED/Nokia LCD
- Estação Meteorológica Portátil Arduino por $10 – DIY com Nano, DHT22, BMP180 e LCD
- eDOT: Relógio de Precisão e Estação Meteorológica Arduino com Controle IR Embutido
- Monitoramento Meteorológico em Tempo Real com Arduino e ThingSpeak IoT