从NodeJS控制Arduino

我试图从NodeJS控制Arduino。

我已经尝试了Duino ,我知道设备已经准备就绪,debugging器显示这些命令已经发送给Arduino,但没有任何反应。

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

请帮助! 谢谢..

我可能能够帮助你,你必须更具体一些你真正想做的事情吗?

你想读取数据? 你想远程控制吗?

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

相反,我已经在我的电脑和机器人之间build立了自己的通信协议。

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

通信是通过发送bytes而不是人类可读的动作来完成的。 所以你要做的第一件事就是设想两者之间的一个小界面。 Bytes是有用的,因为在Arduino方面,你不需要任何转换,而且它们在switch的情况下工作得很好,而string则不是这种情况。

在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])); } 

希望能帮助到你!