0

I'm extremely stumped. I've spent 3 hours googling an answer to my problem. What I have is a arduino that controls some relays. It's controlled by node.js. Everything works great using usb and SerialPort package. What I need to do is drop the USB connection and make this work over Ethernet.

I set up as much as I could and I can ping the arduino through terminal. But where I'm stumped is how to send data (serial data?) to the arduino over the network/ethernet. Before I'd configure my port like... tty/usbmodem141... how do I now send the data to the device on the network? Can I send serial data? Do I need a different package? Thanks guys!

4

1 回答 1

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,但您应该能够弄清楚。

于 2013-10-23T20:02:28.157 回答