-
Notifications
You must be signed in to change notification settings - Fork 3
/
esp8266_udp_rs485.ino
64 lines (52 loc) · 1.56 KB
/
esp8266_udp_rs485.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#define STASSID "your-ssid"
#define STAPSK "your-password"
#define AP // only for access point
#define PIN_EN 2 // or D2 for NodeMCU
WiFiUDP Udp;
IPAddress interfaceAddress;
IPAddress ipAddressMulticast(224, 1, 2, 3);
uint16_t port = 8888;
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet
void setup() {
// put your setup code here, to run once:
digitalWrite(PIN_EN, LOW);
pinMode(PIN_EN, OUTPUT);
Serial.begin(9600); // baudrate
#ifdef AP
WiFi.softAP(STASSID, STAPSK);
interfaceAddress = WiFi.softAPIP();
#else
WiFi.mode(WIFI_STA);
WiFi.begin(STASSID, STAPSK);
while (WiFi.status() != WL_CONNECTED) {
delay(10);
}
interfaceAddress = WiFi.localIP();
#endif
Udp.beginMulticast(interfaceAddress, ipAddressMulticast, port);
}
void loop() {
// put your main code here, to run repeatedly:
int packetSize = Udp.parsePacket();
if (packetSize) {
int n = Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
digitalWrite(PIN_EN, HIGH);
Serial.write(packetBuffer, n);
Serial.flush();
digitalWrite(PIN_EN, LOW);
}
if (Serial.available()) {
char *ptr = packetBuffer;
while (Serial.available()) {
while (Serial.available()) {
*ptr++ = Serial.read();
}
delay(4); // for 9600 baudrate
}
Udp.beginPacketMulticast(ipAddressMulticast, port, interfaceAddress);
Udp.write(packetBuffer, ptr - packetBuffer);
Udp.endPacket();
}
}