Comments (3)
The unexpected behavior in your code could be due to the asynchronous nature of the setTimeout functions and the fact that the sensor's data event is still being processed after you disable it. This might lead to an interference where the sensor is disabled, but the event handler continues to log values.
To address this, you can use a flag to track the sensor's state and prevent logging data when it's disabled. Here's an updated version of your code:
const { Board, Sensor } = require('johnny-five');
const board = new Board({ port: 'COM3' });
board.on('ready', () => {
const moistureSensor = new Sensor({
pin: 'A0',
freq: 100,
});
// Flag to track the sensor state
let isSensorEnabled = true;
moistureSensor.on('data', (value) => {
// Log the value only if the sensor is enabled
if (isSensorEnabled) {
console.log(value);
}
});
setTimeout(() => {
console.log('Disable');
isSensorEnabled = false;
moistureSensor.disable();
}, 1000);
setTimeout(() => {
console.log('Enable');
isSensorEnabled = true;
moistureSensor.enable();
}, 2000);
setTimeout(() => {
console.log('Disable');
isSensorEnabled = false;
moistureSensor.disable();
}, 3000);
});
from johnny-five.
@R-holmes10 Thanks for replying!
I do agree that it's easy to circumvent this bug, but I truly believe that it is a bug.
I'll provide another example, attempting to prove that this is not a problem with the asynchronous nature of the setTimeout function, and that there's reason to believe it's not due to the event still being processed.
In this example I'm using a web socket to communicate between an HTML-page and the node server running johny-five, using the "ws" library (https://www.npmjs.com/package/ws)
The html page has a simple button, which sends a toggle signal to the server using the web socket.
The server responds by enabling or disabling the sensor.
Node server:
const { Board, Sensor } = require("johnny-five");
const WebSocket = require("ws");
const http = require("http");
const board = new Board({
port: "COM4",
});
board.on("ready", () => {
const moistureSensor = new Sensor({
pin: "A0",
freq: 250,
});
moistureSensor.on("data", (value) => {
// Log the value only if the sensor is enabled
console.log(value);
});
// Create an HTTP server
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("WebSocket server is running");
});
const PORT = 3001;
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// Create a WebSocket server by passing the HTTP server object
const wss = new WebSocket.Server({ server });
wss.on("connection", (ws) => {
console.log("Client connected");
ws.on("message", (message) => {
message = JSON.parse(message);
console.log("Received message: ", message);
if (message.topic === "sensor") {
if (message.enabled) {
console.log("Enabling sensor");
moistureSensor.enable();
} else {
console.log("Disabling sensor");
moistureSensor.disable();
}
}
});
// Event handler for WebSocket connection closing
ws.on("close", () => {
console.log("Client disconnected");
});
});
});
HTML file:
<!DOCTYPE html>
<html lang="en">
<script>
let toggle = true;
const socket = new WebSocket("ws://localhost:3001");
const buttonClicked = function () {
toggle = !toggle;
socket.send(JSON.stringify({ topic: "sensor", enabled: toggle }));
};
</script>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button onclick="buttonClicked()">Toggle!</button>
</body>
</html>
Here's the resulting console log:
40
40
Client connected
40
39
39
39
39
39
39
39
Received message: { topic: 'sensor', enabled: false }
Disabling sensor
Received message: { topic: 'sensor', enabled: true }
Enabling sensor
38
37
37
37
37
36
Received message: { topic: 'sensor', enabled: false }
Disabling sensor
36
36
36
[... Keeps running the callback function]
from johnny-five.
from johnny-five.
Related Issues (20)
- Novice ask next how to upload js to hardware HOT 7
- Using PWM and AC DImmer RobotDyn
- Cannot Input Mode Pin 12, 14, 15. ESP8266 HOT 4
- Refactor DS18B20 Temperature Conversion Time Handling
- Usage with Electron of latest J5 versions? HOT 6
- Status of Release?
- Using a Coin selector
- CAN bus with mcp2515 support, and other libraries
- MKR 1010 board HOT 1
- INPUT_PULLUP on digital input pin HOT 12
- I2C Scanner?
- Input pull-up doesn't work on expanders HOT 1
- Unable to use Led.Digits with Multple Boards HOT 4
- Stop stepper while running HOT 2
- Servo animation enqueue is buggy HOT 6
- Calling animation.next inside onloop callback is not working.
- Is there a way to use multiple I2C LCD's HOT 2
- RaspberryPi issue HOT 3
- Intermittent Error Code 31 in GetOverlappedResult
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from johnny-five.