Skip to content

Instantly share code, notes, and snippets.

@TalalMash
Last active October 22, 2023 15:08
Show Gist options
  • Save TalalMash/2c9c63c761f71223ce77f4be42dd6837 to your computer and use it in GitHub Desktop.
Save TalalMash/2c9c63c761f71223ce77f4be42dd6837 to your computer and use it in GitHub Desktop.
ESP8266 TCP to Serial Adapter with WiFi Manager (falls back to AP when station is not available)
// ESP8266 WiFi <-> UART Bridge
// by RoboRemo
// www.roboremo.com
// WiFi Manager Fork
#include <ESP8266WiFi.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager WiFi Configuration Magic
// config: ////////////////////////////////////////////////////////////
#define UART_BAUD 115200
#define packTimeout 5 // ms (if nothing more on UART, then send packet)
#define bufferSize 8192
#define PROTOCOL_TCP
//#define PROTOCOL_UDP
const int port = 9876;
WiFiManager wifiManager;
#ifdef PROTOCOL_TCP
#include <WiFiClient.h>
WiFiServer server(port);
WiFiClient client;
#endif
#ifdef PROTOCOL_UDP
#include <WiFiUdp.h>
WiFiUDP udp;
IPAddress remoteIp;
#endif
uint8_t buf1[bufferSize];
uint16_t i1=0;
uint8_t buf2[bufferSize];
uint16_t i2=0;
void setup() {
delay(500);
Serial.begin(UART_BAUD);
wifiManager.autoConnect("ESP Wi-Fi Serial TCP Bridge");
delay(1000);
#ifdef PROTOCOL_TCP
server.begin(); // start TCP server
#endif
#ifdef PROTOCOL_UDP
udp.begin(port); // start UDP server
#endif
}
void loop() {
#ifdef PROTOCOL_TCP
if(!client.connected()) { // if client not connected
client = server.available(); // wait for it to connect
return;
}
if(client.available()) {
while(client.available()) {
buf1[i1] = (uint8_t)client.read(); // read char from client (RoboRemo app)
if(i1<bufferSize-1) i1++;
}
// now send to UART:
Serial.write(buf1, i1);
i1 = 0;
}
if(Serial.available()) {
while(1) {
if(Serial.available()) {
buf2[i2] = (char)Serial.read(); // read char from UART
if(i2<bufferSize-1) i2++;
} else {
//delayMicroseconds(packTimeoutMicros);
delay(packTimeout);
if(!Serial.available()) {
break;
}
}
}
client.write((char*)buf2, i2);
i2 = 0;
}
#endif
#ifdef PROTOCOL_UDP
int packetSize = udp.parsePacket();
if(packetSize>0) {
remoteIp = udp.remoteIP();
udp.read(buf1, bufferSize);
Serial.write(buf1, packetSize);
}
if(Serial.available()) {
while(1) {
if(Serial.available()) {
buf2[i2] = (char)Serial.read();
if(i2<bufferSize-1) {
i2++;
}
} else {
//delayMicroseconds(packTimeoutMicros);
//Serial.println("dl");
delay(packTimeout);
if(!Serial.available()) {
//Serial.println("bk");
break;
}
}
}
udp.beginPacket(remoteIp, port);
udp.write(buf2, i2);
udp.endPacket();
i2 = 0;
}
#endif
}

Since this is not Telnet protocol disable NL:

image

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment