我正在开发一个具有 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);
当我运行代码时,终端中没有打印任何值。出了什么问题?谢谢。
最佳答案
您不应该将 dgram
套接字的事件大写。
消息
应为消息
聆听
应该是聆听
这是一个小例子
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);
关于javascript - 带有 Node.js 的 Arduino 无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20476581/