Arduino与Node.js不工作

我正在研究一个有Arduino Uno的项目,并使用UDP连接,将数据发送到运行Node.js模块的Mac,以获取数据并将其打印出来。

这是我的Arduino代码:

#include <SPI.h> #include <Ethernet.h> #include <EthernetUdp.h> //Import the necessary packages. byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; //Arduino's MAC address. IPAddress IP(192, 168, 1, 152); //Arduino's IP address. unsigned int arduinoPort = 8888; //Arduino's transmission port. IPAddress recieverIP(192, 168, 1, 77); //Mac's IP address. unsigned int recieverPort = 6000; //Mac's transmission port. EthernetUDP udp; int sensorPin = 2; //The pin on the Arduino the PIR sensor is connected to. int sensorStatus; //The PIR sensor's status. void setup() { Serial.begin(9600); Ethernet.begin(mac, IP); //Starting the Ethernet functionality. udp.begin(arduinoPort); //Starting the UDP server's functionality. } void loop() { Serial.println("YES"); udp.beginPacket(recieverIP, recieverPort); udp.write("YES"); udp.endPacket(); delay(10); } 

这里是我的Node.js模块的代码:

 var dgram = require('dgram'); var server = dgram.createSocket("udp4"); var fs = require('fs'); var crlf = new Buffer(2); crlf[0] = 0xD; crlf[1] = 0xA; server.on("Message", function(msg, rinfo) { console.log("Server got : " + msg.readUInt16LE(0) + " from : " + rinfo.address + " : " + rinfo.port); }); server.on("Listening", function() { var address = server.address(); console.log("Server listening @ " + address.address + " : " + address.port); }); server.bind(6000); 

当我运行代码时,terminal上没有打印任何值。 怎么了? 谢谢。

你不应该大写dgram套接字的事件。

  1. Message应该是message
  2. Listening应该listening

所以这是一个小例子

 var dgram = require("dgram"); var server = dgram.createSocket("udp4"); server.on('listening' /*Correct*/,function(){ console.log("it fires"); }); server.on('Listening' /*Wrong*/,function(){ console.log("it doesn't fire"); }); server.bind(6000);