Elijah Scheele
Published © GPL3+

Connected Door Sensor

Simple BLE door sensor using magnetic reed switch and Arduino/Genuino 101.

BeginnerWork in progress30 minutes1,942
Connected Door Sensor

Things used in this project

Hardware components

Arduino 101
Arduino 101
×1
Magnetic Security Switch
×1
Resistor 10k ohm
Resistor 10k ohm
×1

Software apps and online services

nRF Connect SDK
Nordic Semiconductor nRF Connect SDK

Story

Read more

Schematics

Fritzing Diagram

Fritzing diagram illustrating how everything is connected.

Code

Arduino Code

Arduino
Upload to Arduino 101 or Genuino 101
#include <BLEAttribute.h>
#include <BLECentral.h>
#include <BLECharacteristic.h>
#include <BLECommon.h>
#include <BLEDescriptor.h>
#include <BLEPeripheral.h>
#include <BLEService.h>
#include <BLETypedCharacteristic.h>
#include <BLETypedCharacteristics.h>
#include <BLEUuid.h>
#include <CurieBLE.h>

const int ledPin = 13;
const int switchPin = 2;

BLEPeripheral blePeripheral;
BLEService ledService("19B10010-E8F2-537E-4F6C-D104768A1214");

BLECharCharacteristic ledCharacteristic("19B10011-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);
BLECharCharacteristic switchCharacteristic("19B10012-E8F2-537E-4F6C-D104768A1214", BLERead | BLENotify);





void setup() {
  Serial.begin(9600);

  pinMode(ledPin, OUTPUT);
  pinMode(switchPin, INPUT);

  blePeripheral.setLocalName("DoorSwitch");
  blePeripheral.setAdvertisedServiceUuid(ledService.uuid());
  blePeripheral.addAttribute(ledService);
  blePeripheral.addAttribute(ledCharacteristic);
  blePeripheral.addAttribute(switchCharacteristic);

  ledCharacteristic.setValue(0);
  switchCharacteristic.setValue(0);

  blePeripheral.begin();

  Serial.println("Blueetooth device active, waiting for connections...");
}

void loop() {
  blePeripheral.poll();

  char switchValue = digitalRead(switchPin);
  boolean switchChanged = (switchCharacteristic.value() != switchValue);

  if (switchChanged) {
    ledCharacteristic.setValue(switchValue);
    switchCharacteristic.setValue(switchValue);
  }

  if(ledCharacteristic.written() || switchChanged) {
    if (ledCharacteristic.value()){
      Serial.println("LED on");
      digitalWrite(ledPin, HIGH);
    } else {
      Serial.println("LED off");
      digitalWrite(ledPin, LOW);
    }
  }
 }

Credits

Elijah Scheele

Elijah Scheele

9 projects • 60 followers
Developer interested in all sorts of cool projects.

Comments