当前位置 : 主页 > 网络编程 > JavaScript >

pyroelectric.relay.js

来源:互联网 收集:自由互联 发布时间:2021-06-30
pyroelectric.relay.js // 红外移动传感 FIR800 5v// http://www.espruino.com/Pyroelectric// Relay: low level trigger// @author g8upvar Low_Level = 0;var Hight_Level = 1;var ON = Low_Level;var OFF = Hight_Level;var RELAY = A1;function set
pyroelectric.relay.js
// 红外移动传感 FIR800 5v
// http://www.espruino.com/Pyroelectric
// Relay: low level trigger
// @author g8up

var Low_Level = 0;
var Hight_Level = 1;

var ON = Low_Level;
var OFF = Hight_Level;

var RELAY = A1;

function setRelay(level) {
    digitalWrite(RELAY, level);
}

function active() {
    LED2.write(1);
    setRelay(ON);
}

function deactive() {
    LED2.write(0);
    setRelay(OFF);
}
/**
 * Timer encapsulate
 */
function T(handle, delay) {
    this.delay = delay;
    this.handle = handle;
}

T.prototype.clear = function () {
    if (this._t !== undefined) {
        this._t = undefined;
        clearTimeout(this._t);
    }
};

T.prototype.tick = function () {
    var me = this;
    this.clear();
    this._t = setTimeout(function () {
        me._t = undefined;
        me.handle();
    }, this.delay);
};

function run() {
    var pyroelectric = A0;
    var TURN_OFF_DELAY = 100e3; // 100 sec
    var relayLevel = OFF;
    var TURN_ON_TRIGGER_COUNTER = 0;

    var turnOffTimer = new T(function () {
        relayLevel = OFF;
        deactive();
    }, TURN_OFF_DELAY);

    var turnOnTimer = new T(function () {
        TURN_ON_TRIGGER_COUNTER = 0;
    }, 20e3);// 20sec 后重置计数

    setWatch(function () {
        if (relayLevel === OFF) {
            TURN_ON_TRIGGER_COUNTER++;
            if (TURN_ON_TRIGGER_COUNTER > 2) {// 触发3次再开启
                relayLevel = ON;
                active();
                TURN_ON_TRIGGER_COUNTER = 0;
                turnOnTimer.clear();
            }
            else {
                turnOnTimer.tick();
            }
            console.log("Movement detected", TURN_ON_TRIGGER_COUNTER);
        }
        else {
            turnOffTimer.tick();
        }
    }, pyroelectric, { repeat: true, edge: "rising" });
}

E.on('init', run);
网友评论