Controlling Arduino From NodeJS

Controlling Arduino From NodeJS

本文关键字:NodeJS From Arduino Controlling      更新时间:2023-09-26

我正在尝试从NodeJS控制Arduino。

我已经尝试过Duino,我得到设备已准备就绪,调试器显示命令已成功发送到Arduino,但没有任何反应。

我也尝试过Johnny-Five,它显示设备已连接(在COM8上(,但是on ready事件从未触发。

请帮忙!谢谢。。

我也许能帮助你,你必须更具体地说明你真正想做什么?

是否要读取数据?你想远程控制它吗?

编辑:我也使用Node来控制Arduino,但我没有使用Duino或Johnny-Five,因为它们不适合我的项目。

相反,我在计算机和机器人之间制定了自己的通信协议。

在Arduino上,代码很简单。它检查串行是否可用,如果是,则读取并存储缓冲区。然后,使用switchif/else选择我希望机器人执行的动作(向前移动,向后移动,闪烁led等(。

通信是通过发送bytes而不是人类可读的操作进行的。所以你要做的第一件事是想象两者之间的一个小接口。 Bytes很有用,因为在 Arduino 方面,您不需要任何转换,并且它们非常适合 switch ,而字符串则不是这种情况。

在Arduino方面,你会有类似的东西:(请注意,你需要在某处声明DATA_HEADER(

void readCommands(){
    while(Serial.available() > 0){
        // Read first byte of stream.
        uint8_t numberOfActions;
        uint8_t recievedByte = Serial.read();
        // If first byte is equal to dataHeader, lets do
        if(recievedByte == DATA_HEADER){
            delay(10);
            // Get the number of actions to execute
            numberOfActions = Serial.read();
            delay(10);
            // Execute each actions
            for (uint8_t i = 0 ; i < numberOfActions ; i++){
                // Get action type
                actionType = Serial.read();
                if(actionType == 0x01){
                    // do you first action
                }
                else if(actionType == 0x02{
                    // do your second action
                }
                else if(actionType == 0x03){
                    // do your third action
                }
            }
        }
    }
}

在节点端,你会有类似的东西:(检查串行端口github以获取更多信息(

var dataHeader = 0x0f, //beginning of the data stream, very useful if you intend to send a batch of actions
myFirstAction = 0x01,
mySecondAction = 0x02,
myThirdAction = 0x03;
sendCmdToArduino = function() {
    sp.write(Buffer([dataHeader]));
    sp.write(Buffer([0x03])); // this is the number of actions for the Arduino code
    sp.write(Buffer([myFirstAction]));
    sp.write(Buffer([mySecondAction]));
    sp.write(Buffer([myThirdAction]));
}

希望对您有所帮助!