16. Interface and Application Programming
I often create websites.So HTML5 & javascript are one of the most famillier program language for me. So I tried to use node.js. It is easy for me to connecting the network with Node.js. And actually it is used with many web services. In the future, It is a very useful tool for me bacause I will work in web company.
Programming
setup 1
first, I tried to use serial communication with Node.js. So, I sent signal between Node.js and boards I made.
/*
if you have never used Node.js, install Node.js(https://nodejs.org/en/)
*/
npm install serialport //it is possible to use serial port.
test code
testSerial.js(This program of the function is sending byte to boards I made last week. Then, led blink.)
'use strict';
var serialport = require('serialport');
var SerialPort = serialport.SerialPort;
var parsers = serialport.parsers;
var port = new SerialPort('/dev/cu.usbmodemfd121', {
baudrate: 9600,
parser: parsers.readline('\r\n')
});
port.on('open', function() {
console.log('Port open');
});
port.on('data', function(data) {
console.log(data);
});
setup 2
Second, I tried to connect between asynchronous server created with the socket.io package of Node.js and boards I made.
/*
if you have never used Node.js, install Node.js(https://nodejs.org/en/)
*/
npm install serialport //it is possible to use serial port.
npm install socket.io //it is possible to use realtime communication with Node.js.
npm install express // it is possible to use express frameworks
express -e ex16 // generate web application with express
coding
index.ejs(this is UI and serial communication program file)
<body>
<div class=\"wrapper\">
<div id=\"button1\" class=\"button\"><p>PUSH ME!!</p></div>
<div id=\"button2\" class=\"button\"><p>PUSH ME!!</p></div>
</div>
<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js\"></script>
<script src=\"http://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js\"></script>
<script src=\"/socket.io/socket.io.js\"></script>
<script>
var socket = io.connect(\'192.168.11.20:3000\');
socket.on(\'news\',function(data){
console.log(data);
socket.emit(\'my other event\',{my:\'data\'});
});
$(function(){
$(\"#button1\").on(\'click\', function(){
socket.emit(\'my other event\',{button:\'0\'});
});
$(\"#button2\").on(\'click\', function(){
socket.emit(\'my other event\',{button:\'1\'});
});
});
</script>
</body>
reference
DOWNLOAD
Running
Finally, I controlled LEDs with a smartphone. I open a client page such a UI window with it in local network. if I tapped a red button, sent byte '1' and a red led blinked. if I tapped a blue button, sent byte '0' and a blue led blinked.