【问题标题】:Can't control the LED by a single html file and johnny five无法通过单个 html 文件和约翰尼五号控制 LED
【发布时间】:2017-03-16 20:50:28
【问题描述】:

我是这个的新手。我找到了一些代码来控制由单个 html 文件引导的 Arduino。他们说我们必须使用 johnny-5 和 node-js 协议来控制它。但是我发现这种方式有问题,我成功连接到Arduino并打开本地主机。但是,我只是找到了几个按钮,并且无法控制 LED。我会尝试解决它,但什么也没发生。

这是我的源代码 The code

<html>
   <head>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
      <script src="/socket.io/socket.io.js"></script>
      <script>
         $(document).ready(function() {
           var socket = io.connect('http://localhost');
           $('#button').click(function(e){
             socket.emit('click');
             e.preventDefault();
           });
         });  
      </script>
   </head>
   <body>
      <button id="button" href="#">LED ON/OFF</button>
   </body>
</html>

var app = require('http').createServer(handler),
    io = require('socket.io').listen(app),
    fs = require('fs'),
    five = require('johnny-five');

app.listen(8080);

function handler(req, res) {
    fs.readFile(__dirname + '/index.html',
        function(err, data) {
            if (err) {
                res.writeHead(500);
                return res.end('Error loading index.html');
            }

            res.writeHead(200);
            res.end(data);
        });
}

board = new five.Board();

board.on("ready", function() {
    led = new five.Led(13);

    io.sockets.on('connection', function(socket) {
        socket.on('click', function() {
            led.toggle();
        });
    });
});

【问题讨论】:

    标签: html node.js arduino johnny-five


    【解决方案1】:

    您在端口“8080”上运行您的服务器,但您在默认端口 (80) 上连接到 socket.io。我相信这可能是问题所在。尝试将 html 中的行更改为:

          var socket = io.connect('http://localhost:8080');
    

    此外,如果您的浏览器控制台中有任何错误,显示此消息会很有帮助。

    【讨论】:

    • 宁可让 Arduino 监听端口 80。那么您不必指定要连接的端口,因为 80 是 Web 应用程序的默认端口。
    猜你喜欢
    • 2018-10-18
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 2012-08-08
    • 1970-01-01
    相关资源
    最近更新 更多