The setInterval() method repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. In our case we write HIGH on pin 13 each 500ms and LOW on pin 13 each 750ms:
socket.on("blinkOn", function(){
timer1 = setInterval(function () {board.digitalWrite(13, board.HIGH);}, 500);
timer2 = setInterval(function () {board.digitalWrite(13, board.LOW);}, 750);
});
Clearing the setInterval, i.e. stopping the execution:
clearInterval(timer1);
clearInterval(timer2);
var http = require("http").createServer(handler); // on req - handler - function to handle events
var io = require("socket.io").listen(http); // socket library
var fs = require("fs"); // variable for file system for providing html
var firmata = require("firmata");
console.log("Starting the code");
var board = new firmata.Board("/dev/ttyACM0", function(){
console.log("Connecting to Arduino");
console.log("Activation of Pin 13");
board.pinMode(13, board.MODES.OUTPUT); // pin13 as out
});
// we should define handler function which is an argument in the first line
// to specify how events are handled
// handler is similar function as in example01.js -> http.createServer(function(req, res){...
function handler(req, res) {
fs.readFile(__dirname + "/assignment08.html",
function (err, data) {
if (err) {
res.writeHead(500, {"Content-Type": "text/plain"});
return res.end("Error loading html page.");
}
res.writeHead(200);
res.end(data);
})
}
var timer1;
var timer2;
http.listen(8080); // server will listen on port 8080
io.sockets.on("connection", function(socket) {
socket.on("commandToArduino", function(commandNo){
if (commandNo == "1") {
board.digitalWrite(13, board.HIGH); // write high on pin 13
}
if (commandNo == "0") {
board.digitalWrite(13, board.LOW); // write low on pin 13
}
});
socket.on("blinkOn", function(){
timer1 = setInterval(function () {board.digitalWrite(13, board.HIGH);}, 500);
timer2 = setInterval(function () {board.digitalWrite(13, board.LOW);}, 750);
});
socket.on("blinkOff", function(){
clearInterval(timer1);
clearInterval(timer2);
board.digitalWrite(13, board.LOW);
});
});
<!DOCTYPE html>
<meta charset = utf8>
<html>
<head>
<title>Example with buttons</title>
</head>
<body>
<button id="buttonOn" style="width: 80px;" onClick="on()">On</button>
<button id="buttonOff" style="width: 80px;" onClick="off()">Off</button>
<br>
<button id="buttonBlinkOn" style="width: 80px;" onClick="blinkOn()">B On</button>
<button id="buttonBlinkOff" style="width: 80px;" onClick="blinkOff()">B Off</button>
<br>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect("192.168.254.133:8080"); // connect via socket
function on () {
socket.emit("commandToArduino", 1);
}
function off () {
socket.emit("commandToArduino", 0);
}
function blinkOn () {
socket.emit("blinkOn");
}
function blinkOff () {
socket.emit("blinkOff");
}
</script>
</body>
</html>