1
0

Demo.ino 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. --------------
  3. WebSerial Demo
  4. --------------
  5. Skill Level: Beginner
  6. This example provides with a bare minimal app with WebSerial functionality.
  7. Github: https://github.com/ayushsharma82/WebSerial
  8. Wiki: https://docs.webserial.pro
  9. Works with following hardware:
  10. - ESP8266
  11. - ESP32
  12. WebSerial terminal will be accessible at your microcontroller's <IPAddress>/webserial URL.
  13. Checkout WebSerial Pro: https://webserial.pro
  14. */
  15. #include <Arduino.h>
  16. #if defined(ESP8266)
  17. #include <ESP8266WiFi.h>
  18. #include <ESPAsyncTCP.h>
  19. #elif defined(ESP32)
  20. #include <WiFi.h>
  21. #include <AsyncTCP.h>
  22. #endif
  23. #include <ESPAsyncWebServer.h>
  24. #include <WebSerial.h>
  25. AsyncWebServer server(80);
  26. const char* ssid = ""; // Your WiFi SSID
  27. const char* password = ""; // Your WiFi Password
  28. unsigned long last_print_time = millis();
  29. void setup() {
  30. Serial.begin(115200);
  31. WiFi.mode(WIFI_STA);
  32. WiFi.begin(ssid, password);
  33. if (WiFi.waitForConnectResult() != WL_CONNECTED) {
  34. Serial.printf("WiFi Failed!\n");
  35. return;
  36. }
  37. // Once connected, print IP
  38. Serial.print("IP Address: ");
  39. Serial.println(WiFi.localIP());
  40. server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
  41. request->send(200, "text/plain", "Hi! This is WebSerial demo. You can access webserial interface at http://" + WiFi.localIP().toString() + "/webserial");
  42. });
  43. // WebSerial is accessible at "<IP Address>/webserial" in browser
  44. WebSerial.begin(&server);
  45. /* Attach Message Callback */
  46. WebSerial.onMessage([&](uint8_t *data, size_t len) {
  47. Serial.printf("Received %u bytes from WebSerial: ", len);
  48. Serial.write(data, len);
  49. Serial.println();
  50. WebSerial.println("Received Data...");
  51. String d = "";
  52. for(size_t i=0; i < len; i++){
  53. d += char(data[i]);
  54. }
  55. WebSerial.println(d);
  56. });
  57. // Start server
  58. server.begin();
  59. }
  60. void loop() {
  61. // Print every 2 seconds (non-blocking)
  62. if ((unsigned long)(millis() - last_print_time) > 2000) {
  63. WebSerial.print(F("IP address: "));
  64. WebSerial.println(WiFi.localIP());
  65. WebSerial.printf("Uptime: %lums\n", millis());
  66. WebSerial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap());
  67. last_print_time = millis();
  68. }
  69. WebSerial.loop();
  70. }