[英]Node.js: how can I delay (not sleep) from one line to another to pulse stepper motor in a loop
I'm controlling a stepper motor with onoff in a Raspberry Pi 3B+ and want to delay between setting pulse high and then low within a loop.我在 Raspberry Pi 3B+ 中控制带 onoff 的步进电机,并希望在循环内设置脉冲高电平和低电平之间进行延迟。
for (i=0; i < steps; i++) {
pinPul.writeSync(1);
delay here 10 milliseconds
pinPul.writeSync(0);
delay another 10 milliseconds
}
I don't want to stop the execution of any of the other stuff that's going on in the program during the delay.我不想在延迟期间停止执行程序中正在发生的任何其他事情。
Node.js uses a event loop. Node.js 使用事件循环。 And you want to use sync functions that waits.
并且您想使用等待的同步功能。
The default approach in js/node is using setTimeout() but it relies on callbacks and cannot be used on a for loop. js/node 中的默认方法是使用setTimeout()但它依赖于回调并且不能用于 for 循环。 To fix this you need to use the modern async/await .
要解决此问题,您需要使用现代的async/await 。
async function sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
}
async function ledLoop() {
for (i=0; i < steps; i++) {
pinPul.writeSync(1);
await sleep(10);
pinPul.writeSync(0);
await sleep(10);
}
}
ledLoop();
Just a comment.只是一个评论。 10ms is too fast for the human eye.
10ms 对人眼来说太快了。 Change to 1000ms for better testing.
更改为 1000 毫秒以进行更好的测试。
You could please help me with my code?你能帮我写代码吗?
In the form below the code blocks until the time has passed.在代码块下方的表格中,直到时间过去。
I wanted to make the code to not block and executes everything else.我想让代码不阻塞并执行其他所有内容。 What is the problem?
问题是什么?
const dotenv = require('dotenv');
dotenv.config();
const preferenceService = require("../services/preference-service")
let rpio = {};
if (!process.env.DEVELOPMENT) rpio = require('rpio');
exports.irrigate = async (irrigationTimeInSeconds, sensorName) => {
const preferences = await preferenceService.getPreference(sensorName)
console.log("Pornire irigare - " + preferences.sensorName + "...")
rpio.open(preferences.signalPin, rpio.OUTPUT, rpio.HIGH);
async function sleep(irrigationTimeInSeconds) {
return new Promise(resolve => {
setTimeout(resolve, irrigationTimeInSeconds);
});
}
async function irigare() {
rpio.write(preferences.signalPin, rpio.LOW);
await rpio.sleep(irrigationTimeInSeconds);
rpio.write(preferences.signalPin, rpio.HIGH);
rpio.close(preferences.signalPin);
}
irigare();
return "Success"
}
exports.getSensorNames = async () => {
const preferences = await preferenceService.getPreferences()
return preferences.map(preference => preference.sensorName)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.