我非常难过。我花了3个小时谷歌搜索我的问题的答案。我所拥有的是控制一些继电器的arduino。它由node.js控制。使用usb和SerialPort包,一切都很好用。我需要做的是放弃USB连接并使其在以太网上工作。
我尽可能多地设置,我可以通过终端ping arduino。但我难倒的地方是如何通过网络/以太网向arduino发送数据(串行数据?)。在我将端口配置为... tty / usbmodem141之前......我现在如何将数据发送到网络上的设备?我可以发送串行数据吗?我需要一个不同的包吗?谢谢你们!
答案 0 :(得分:3)
这是一张适合我的草图。
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
byte arduinoMac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress arduinoIP(10, 0, 0, 19); // desired IP for Arduino
unsigned int arduinoPort = 8888; // port of Arduino
IPAddress receiverIP(10, 0, 0, 13); // IP of udp packets receiver
unsigned int receiverPort = 6000; // port to listen on my PC
EthernetUDP Udp;
void setup() {
Ethernet.begin(arduinoMac,arduinoIP);
Udp.begin(arduinoPort);
}
void loop() {
Udp.beginPacket(receiverIP, receiverPort); //start udp packet
Udp.print(String(analogRead(A0), DEC)); //write sensor data to udp packet
Udp.write(",");
Udp.print(String(analogRead(A1), DEC)); //write sensor data to udp packet
Udp.endPacket(); // end packet
delay(3000);
}
要在另一端登录,我使用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
function getDateTime() {
var date = new Date();
var hour = date.getHours();
hour = (hour < 10 ? "0" : "") + hour;
var min = date.getMinutes();
min = (min < 10 ? "0" : "") + min;
var sec = date.getSeconds();
sec = (sec < 10 ? "0" : "") + sec;
var year = date.getFullYear();
var month = date.getMonth() + 1;
month = (month < 10 ? "0" : "") + month;
var day = date.getDate();
day = (day < 10 ? "0" : "") + day;
return year + "/" + month + "/" + day + " " + hour + ":" + min + ", ";
}
server.on("error", function (err) {
console.log("server error:\n" + err.stack);
server.close();
});
server.on("message", function (msg, rinfo) {
console.log(getDateTime() + msg + " from " +
rinfo.address + ":" + rinfo.port);
fs.appendFile("mydata.txt",getDateTime() + msg + crlf, encoding='utf8',function(err){});//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);
// server listening 10.0.0.13:6000
你必须调整你的Arduino和主机的IP,但你应该能够搞清楚。