Taron Foxworth
Published

Detecting Motion with a PIR Sensor, ESP8266, and Mongoose OS

A walk through building a motion detector with an ESP8266, PIR sensor, Mongoose OS, Javascript, and the Losant IoT Platform.

BeginnerFull instructions provided1 hour4,329
Detecting Motion with a PIR Sensor, ESP8266, and Mongoose OS

Things used in this project

Hardware components

NodeMCU
×1
Breadboard (generic)
Breadboard (generic)
×1
Jumper wires (generic)
Jumper wires (generic)
×1
PIR Motion Sensor (generic)
PIR Motion Sensor (generic)
×1

Software apps and online services

Mongoose OS
Mongoose OS
Losant Platform
Losant Platform

Story

Read more

Schematics

Wiring

Code

Code snippet #2

Plain text
load('api_config.js');
load('api_gpio.js');
load('api_mqtt.js');
load('api_timer.js');

// Set the pin number. On the NodeMCU D1 is pin 5.
// See pinout: https://pradeepsinghblog.files.wordpress.com/2016/04/nodemcu_pins.png?
let pirSensor = 5;

// Blink built-in LED every second
GPIO.set_mode(pirSensor, GPIO.MODE_INPUT);

// Look for motion every 2 seconds.
Timer.set(2000 /* 2 sec */ , true /* repeat */ , function () {
  let motion = GPIO.read(pirSensor);
  let topic = '/losant/' + Cfg.get('device.id') + '/state';
  let message = JSON.stringify({
   data: {
     movement: motion
   }
  });
  let ok = MQTT.pub(topic, message, 1);
  print('Published:', ok ? 'yes' : 'no', 'topic:', topic, 'message:', message);
}, null);

Code snippet #4

Plain text
{
   "wifi": {
     "sta": {
     "enable": true,
     "ssid": "WIFI_SSID",
     "pass": "WIFI_PASSWORD"
   }
  },
  "device": {
     "id": "LOSANT_DEVICE_ID"
  },
  "debug": {
     "stdout_topic": "",
     "stderr_topic": ""
  },
  "mqtt": {
     "enable": true,
     "client_id": "LOSANT_DEVICE_ID",
     "user": "LOSANT_ACCESS_KEY",
     "pass": "LOSANT_ACCESS_SECRET",
     "ssl_ca_cert": "ca.pem"
  }
}

Github

https://github.com/cesanta/mjs

Github

https://github.com/Losant/losant-mongoose-motion-sensor

Credits

Taron Foxworth

Taron Foxworth

0 projects • 6 followers

Comments