连接顺序
Arduino> W5100以太网屏蔽>笔记本电脑>服务器
Arduino源代码:
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
byte arduinoMac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress arduinoIP(192, 168, 0,3); // desired IP for Arduino
unsigned int arduinoPort = 8888; // port of Arduino
IPAddress receiverIP(192, 168, 0, 11); // IP of udp packets receiver
unsigned int receiverPort = 6000; // port to listen on my PC
EthernetUDP Udp;
int sensorPin = A0; //define sensor pin
int sensorValue;
void setup() {
Ethernet.begin(arduinoMac,arduinoIP);
Udp.begin(arduinoPort);
}
void loop() {
sensorValue = digitalRead(sensorPin);//read sensor value from 0 to 1023
Udp.beginPacket(receiverIP, receiverPort); //start udp packet
Udp.write(sensorValue); //write sensor data to udp packet
Udp.endPacket(); // end packet
delay(1000);
}
NODE.JS服务器文件:
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
var fs = require('fs');
var crlf = new Buffer(2);
crlf[0] = 0xD; //CR - Carriage return character
crlf[1] = 0xA; //LF - Line feed character
server.on("message", function (msg, rinfo) { //every time new data arrives do this:
console.log("server got: " + msg + " from " + rinfo.address + ":" + rinfo.port); // you can comment this line out
fs.appendFile('mydata.txt', msg + crlf, encoding='utf8');//write the value to file and add CRLF for line break
});
server.on("listening", function () {
var address = server.address();
console.log("server listening " + address.address + ":" + address.port);
});
server.bind(6000); //listen to udp traffic on port 6000
CMD SERVER正在运行: Print..
CMD IPCONFIG: Print..
问题是来自arduino的消息未到达服务器。它应该可以正常工作,我已经看到了几个具有相似源代码的不同网站。 我需要在笔记本电脑中进行一些配置吗?我确实在防火墙中打开了一个端口6000,但是什么都没发生。