Skip to content

Instantly share code, notes, and snippets.

@rakeshpai
Created July 9, 2016 07:55
Show Gist options
  • Save rakeshpai/500a2771e9205f57d84449fdaca0bf8d to your computer and use it in GitHub Desktop.
Save rakeshpai/500a2771e9205f57d84449fdaca0bf8d to your computer and use it in GitHub Desktop.
Code to randomly turn on or off an LED. With an extremely useful HTTP API. Uses Espruino, running on an ESP8266 (ESP-03).
var wifi = require("Wifi"),
ledPin = D14,
buttonPin = D0,
ssid = "...",
password = "...";
var led = (function() {
var pulseIntervalHandle,
startTime;
return {
on: function() {
digitalWrite(ledPin, 1);
},
off: function() {
digitalWrite(ledPin, 0);
},
startPulse: function() {
if(pulseIntervalHandle) return;
startTime = Date.now();
pinMode(ledPin, "output");
pulseIntervalHandle = setInterval(function() {
var ledBrightness = Math.sin((Date.now() - startTime)/500);
analogWrite(ledPin, Math.abs(ledBrightness), {forceSoft: true});
}, 20);
},
stopPulse: function() {
if(pulseIntervalHandle) {
clearInterval(pulseIntervalHandle);
pulseIntervalHandle = null; // Interestingly, Esprino expects you to do the right thing here.
}
pinMode(ledPin, "output"); // Not sure why this is needed, but it does the trick.
digitalWrite(ledPin, 0);
},
terminalError: function() {
setInterval(function() {
digitalWrite(ledPin, !digitalRead(ledPin));
}, 250);
}
};
})();
var flipARandomBit = (function() {
var isFlipping = false,
flipDuration = 3000,
queue = [];
return function(done) {
if(typeof done == "function") queue.push(done);
if(isFlipping) return;
isFlipping = true;
led.startPulse();
console.log("Flipping a bit...");
setTimeout(function() {
led.stopPulse();
var ledState = Math.random()<0.5;
ledState?led.on():led.off();
console.log("Flip result: ", ledState);
var queueItem;
while(queueItem = queue.pop()) {
queueItem(ledState);
}
isFlipping = false;
}, flipDuration);
};
})();
function connectToWifi() {
console.log("Connecting to " + ssid + "...");
led.startPulse();
wifi.connect(ssid, {password: password}, function(err) {
led.stopPulse();
if(err) {
console.log("Couldn't connect to " + ssid);
console.log(err);
led.terminalError();
return;
}
console.log("Connected to " + ssid + ". Starting an HTTP server.");
setTimeout(function() {
var server = require("http").createServer(handleRequests);
server.listen(80);
}, 1000);
wifi.getIP(function(station) {
console.log("My IP is " + station.ip);
});
});
wifi.stopAP();
wifi.setHostname("bitflipper");
}
function handleRequests(req, res) {
console.log("Received request for " + req.url);
if(req.url == "/") {
res.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Content-type": "text/html"
});
res.write("<title>BitFlipper</title>");
res.write("<style>.result,progress{height:30px}body{width:100%;height:100%;display:flex;align-items:center;justify-content:center;background:#D6D7DC;font-family:Tahoma,Geneva,sans-serif}.centered{max-width:50%;text-align:center;background:rgba(255,255,255,.6);padding:30px}h1{color:#3A4E6E;font-size:4em;margin:0 0 20px}button{background:#03C03C;margin:0 0 25px;padding:15px 10px;width:180px;color:#fff;cursor:pointer;font-size:1.25em;border:0}progress{width:100%;display:none}</style>");
res.write("<body><div class='centered'><h1>BitFlipper</h1><button>Flip A Bit</button><div class='result'><progress></progress><div id='result'></div></div></body>");
res.write("<script>!function(){function e(e,t){var n=new XMLHttpRequest;n.open('get',e),n.addEventListener('load',function(){t(JSON.parse(n.responseText))}),n.send()}document.querySelector('button').addEventListener('click',function(){var t=document.querySelector('#result'),n=document.querySelector('progress');n.style.display='block',t.style.display='none',e('/flip',function(e){t.innerHTML='Result: <b>'+e.result.toString()+'</b>',n.style.display='none',t.style.display='block'})},!1)}();</script>");
res.end();
console.log("Responded with home page");
} else if(req.url == "/flip") {
flipARandomBit(function(result) {
res.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Content-type": "application/json"
});
res.end(JSON.stringify({result: result}));
console.log("Responded to /flip with JSON");
});
} else {
res.writeHead(404, {"Content-type": "text/plain"});
res.end("404 - Not Found");
console.log("Responded to " + req.url + " with 404");
}
}
E.on("init", function() {
connectToWifi();
setWatch(flipARandomBit, buttonPin, {repeat: true, edge: "falling"});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment