我第一次使用node.js和一个简单的网站来控制电机。
在网站上有2个按钮:“左”和“右”。您必须按住“左”或“右”按钮才能转动电机。当你按下按钮时电机停止。 电机连接到服务器上串行端口上的Arduino。 它有效,但
当我在手机上使用它并垃圾邮件按钮时,服务器有时会停止响应所有人,直到我重新启动服务器。由于WiFi延迟,我认为功能调用太快。所以我尝试在Chrome控制台中调用这些功能。
LeftPressed();LeftReleased();LeftPressed();LeftReleased();
事实上,在运行它们几次后服务器停止响应。 没有错误,没有崩溃..
当我删除motorPort.write(message);
时,服务器会保持响应。
如何阻止服务器停止响应?
function LeftPressed() {
socket.emit('steer', { left: true });
}
function LeftReleased() {
socket.emit('steer', { left: false });
}
function RightPressed() {
socket.emit('steer', { right: true });
}
function RightReleased() {
socket.emit('steer', { right: false });
}
const SerialPort = require("serialport");
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server)
const motorPort = new SerialPort('/dev/arduinoUnoMicroUSB', {
baudrate: 9600,
});
app.use(express.static('web'));
server.listen(8081, function () {
console.log("Server running...");
});
io.on('connection', function (socket) {
socket.on('steer', function (data) {
var message = "2"; //stop
if (data.left != undefined) {
console.log("Left: " + data.left); //log to Console (below)
if (data.left) {
message = "1" //turn left
}
}
if (data.right != undefined) {
console.log("Right: " + data.right);
if (data.right) {
message = "3"; //turn right
}
}
motorPort.write(message); //send message over serial port
});
});
控制台输出示例:点击“左”按钮
Server running...
Left: true //pressed (motor turning left)
Left: false //released (motor stops)
答案 0 :(得分:0)
我得到了它。它不是100%完美,但至少服务器不断响应。如果您认为有更好的方法,我总是乐于改进。
const SerialPort = require("serialport");
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const motorPort = new SerialPort('/dev/arduinoUnoMicroUSB', {
baudrate: 9600,
});
app.use(express.static('web'));
server.listen(8081, function () {
console.log("Server running...");
});
var ready = true;
var NotSendMessages = [];
io.on('connection', function (socket) {
socket.on('steer', function (data) {
var message = "2"; //stop
if (data.left != undefined) {
console.log("Left: " + data.left);
if (data.left) {
message = "1" //turn left
}
}
if (data.right != undefined) {
console.log("Right: " + data.right);
if (data.right) {
message = "3"; //turn right
}
}
if (!ready) {
console.log("cats!!!");
NotSendMessages.push(message);
} else {
send(message);
}
});
});
function send(message) {
motorPort.write(message, function () {
ready = false;
motorPort.drain(function () {
motorPort.flush(function () {
ready = true;
});
});
});
}
setInterval(function () {
if (NotSendMessages.length > 0 && ready) {
send(NotSendMessages.shift());
}
}, 50);