Skip to content

Instantly share code, notes, and snippets.

@akimichi
Last active April 18, 2017 12:06
Show Gist options
  • Save akimichi/5e8b16be72cfe4984b1fd0157b83a3f1 to your computer and use it in GitHub Desktop.
Save akimichi/5e8b16be72cfe4984b1fd0157b83a3f1 to your computer and use it in GitHub Desktop.
express4でjohnny-fiveを使う
"use strict";
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const flash = require('connect-flash');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const errorHandler = require('errorhandler');
const config = require('config');
const morgan = require('morgan');
// view setting
app.set('view engine', 'pug');
app.set('views', __dirname + '/views');
app.use(morgan('dev'));
app.use(express.static(__dirname + '/public'));
// POSTでdataを受け取るための記述
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', function (req, res) {
console.log('GET /');
res.render('index', {
title: 'コントローラ',
});
});
// johnny-fiveのコード
const five = require("johnny-five"); // Load the node library that lets us talk JS to the Arduino
const board = new five.Board(); // Connect to the Arduino using that library
board.on("ready", function() { // Once the computer is connected to the Arduino
let temperature = new five.Thermometer({
pin: "A0",
toCelsius: function(raw) {
var val = ((raw * 5 / 1024) - 0.6) * 100; // 温度計算
return Math.round(val * 10) / 10; // 小数点第2位以下四捨五入
}
});
io.on('connection', (client) => {
client.on('join', (handshake) => {
console.log(handshake);
});
// Every time a 'temperature' event is sent, listen to it and grab its new values
temperature.on("data", () => {
// console.log(temperature.celsius + "°C");
client.emit('temperature', temperature.celsius);
});
});
})
// 5001番を指定
const port = process.env.PORT || 5001;
http.listen(port);
extends layout
block append scripts
script(src='/js/socket.io.js')
script(src="/js/temperature.js")
block append style
link(rel='stylesheet', href='/css/style.css')
block content
#temperature
$(function(){
var server = io("http://octopi.local:5001");
server.on('temperature', (value) => {
$('#temperature').text(value);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment