【问题标题】:Controlling Arduino From NodeJS从 NodeJS 控制 Arduino
【发布时间】:2013-10-04 05:34:03
【问题描述】:

我正在尝试从 NodeJS 控制 Arduino。

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

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

请帮忙! 谢谢..

【问题讨论】:

    标签: javascript node.js serial-port arduino npm


    【解决方案1】:

    如果你必须更具体地了解你真正想做的事情,我或许可以帮助你?

    您要读取数据吗?你想遥控吗?

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

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

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

    通信是通过发送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
                    }
                }
            }
        }
    }
    

    在节点方面,您将拥有类似的内容:(查看serialport 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]));
    }
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      • 2016-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      相关资源
      最近更新 更多