我是C#和PLC程序员,但我需要为公司工作Arduino。
我有两个Arduino MEGA和两个以太网屏蔽: (https://www.gotronic.fr/art-shield-ethernet-ef02029-23481.htm)
我试图与他人交流。
编辑:我的目标是:从客户端向服务器发送数字和模拟信号。
我尝试了示例示例代码(WebServer和WebClient),我更改了MAC地址,因为示例中它们相同,影响IP地址,删除了DHCP部分。我可以在客户端Arduino上看到TX指示灯,但是在服务器Arduino上没有RX LED。我使用RJ45直电缆。可以吗?
您对我有什么建议吗?或者被别人窃听可以帮到我吗?
客户代码:
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
EthernetUDP Udp;
byte mac[] = {0x90, 0xA2, 0xDA, 0x0D, 0x5C, 0x18};
IPAddress ip(192,168,1,15);
unsigned int localPort = 8888;
IPAddress remoteIP(192,168,1,16);
unsigned int remotePort = 8888;
EthernetClient client;
void setup(){
Serial.begin(9600);
Serial.println("****************");
Serial.println("Serial OK");
//Ethernet.init(10);
Ethernet.begin(mac,ip);
delay(1000);
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
if (client.connect(remoteIP, 8888))
{
Serial.println("Client was connected");
}
else
{
Serial.println("Client was not connected");
}
Serial.print("IP : ");
Serial.println(Ethernet.localIP());
Udp.begin(localPort);
}
void loop(){
/*
Udp.beginPacket(remoteIP, remotePort);
Udp.println("Message UDP");
Serial.println("Message UDP");
Udp.endPacket();*/
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write("Hello world");
Udp.endPacket();
delay(2000);
}
服务器代码:
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
// Server MAC adress
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// Server IP adress
IPAddress ip(192,168,1,16);
// local port to listen on
unsigned int localPort = 8888;
EthernetUDP Udp;
//buffer to hold incoming packet,
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
void setup() {
Serial.begin(9600);
//Ethernet.init(10);
delay(1000);
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
delay(1000);
Udp.begin(localPort);
}
void loop() {
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i =0; i < 4; i++)
{
Serial.print(remote[i], DEC);
if (i < 3)
{
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
Serial.println("Contents:");
Serial.println(packetBuffer);
}
else
{
Serial.println("Didn't receive anything...");
Serial.println(String(packetSize));
}
}