[Week 2] BLE Peripheral — Weather Station

I created a simple BLE weather station peripheral that uses a DHT22 sensor to get temperature and humidity values. The peripheral gets sensor values every 1 second and broadcasts the values over BLE.

Arduino code

// add libs
#include 
#include 

// define IO pins
#define HUMIDITY_SENSOR_PIN 6

// initialize vars
unsigned long previousMillis = 0;
unsigned short interval = 2500;

// initialize DHT sensor
DHT dht(HUMIDITY_SENSOR_PIN, DHT22);  // on pin 6

// initialize BLE peripheral and service
BLEPeripheral blePeripheral;
BLEService tempService = BLEService("FF99");

// define BLE service characteristics
BLEFloatCharacteristic temperatureCharacteristic = BLEFloatCharacteristic("BBB1", BLERead | BLENotify | BLEBroadcast);
BLEDescriptor temperatureDescriptor = BLEDescriptor("2901", "temp F*");
BLEFloatCharacteristic humidityCharacteristic = BLEFloatCharacteristic("BBB2", BLERead | BLENotify | BLEBroadcast);
BLEDescriptor humidityDescriptor = BLEDescriptor("2901", "humidity %");

void setup() {
  Serial.begin(9600);
  Serial.println(F("Serial online..."));
  dht.begin();
  Serial.println(F("DHT started!"));

  // set name and advertise BLE peripheral
  blePeripheral.setLocalName("dht-temp");
  blePeripheral.setDeviceName("dht-temp");
  blePeripheral.setAdvertisedServiceUuid(tempService.uuid());

  // add BLE service and characteristic
  blePeripheral.addAttribute(tempService);
  blePeripheral.addAttribute(temperatureCharacteristic);
  blePeripheral.addAttribute(temperatureDescriptor);
  blePeripheral.addAttribute(humidityCharacteristic);
  blePeripheral.addAttribute(humidityDescriptor);

  //temperatureCharacteristic.broadcast();
  //humidityCharacteristic.broadcast();
  blePeripheral.begin();
}

void loop() {
  blePeripheral.poll();
  Serial.println("LOOP");

  // read sensors @ 2 sec interval
  if (millis() - previousMillis > interval) {
    getTemp();
    getHumidity();
    previousMillis = millis();
  }
}

void getTemp() {
  // read sensor val
  float temperature = dht.readTemperature(true);  // true = fahrenheit

  if (isnan(temperature)) {
    Serial.println("DHT Temp not found...");
    temperature = 0;
    temperatureCharacteristic.setValue(temperature);
  } else if (temperatureCharacteristic.value() != temperature) {
    temperatureCharacteristic.setValue(temperature);
    Serial.print("Temp: ");
    Serial.print(temperature);
    Serial.print(" *F");
    Serial.println();
  }
}

void getHumidity() {
  // read sensor val
  float humidity = dht.readHumidity();

  if (isnan(humidity)) {
    Serial.println("DHT Humidity not found...");
    humidity = 0;
    humidityCharacteristic.setValue(humidity);
  } else if (humidityCharacteristic.value() != humidity) {
    humidityCharacteristic.setValue(humidity);
    Serial.print("Humidity: ");
    Serial.print(humidity);
    Serial.println();
  }
}

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Fritzing diagram

February 3, 2018

Leave a Reply