metalx1000

ESP8266 IR Receiver with WIFI Manager

Mar 16th, 2022 (edited)
1,855
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 10.18 KB | None | 0 0
  1. /*
  2.  * IRremoteESP8266: IRrecvDumpV2 - dump details of IR codes with IRrecv
  3.  * An IR detector/demodulator must be connected to the input kRecvPin.
  4.  *
  5.  * Copyright 2009 Ken Shirriff, http://arcfn.com
  6.  * Copyright 2017-2019 David Conran
  7.  *
  8.  * Example circuit diagram:
  9.  *  https://github.com/crankyoldgit/IRremoteESP8266/wiki#ir-receiving
  10.  *
  11.  * Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009,
  12.  * https://github.com/crankyoldgit/IRremoteESP8266
  13.  * Combined with https://github.com/tzapu/WiFiManager for easier use
  14.  * By Kris Occhipinti 2022 https://pastebin.com/edit/cjiRBCbe
  15.  */
  16.  
  17. #include <Arduino.h>
  18. #include <assert.h>
  19. #include <IRrecv.h>
  20. #include <IRremoteESP8266.h>
  21. #include <IRac.h>
  22. #include <IRtext.h>
  23. #include <IRutils.h>
  24. #include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
  25. #include <ESP8266WebServer.h>
  26. ESP8266WebServer server(80);
  27.  
  28. String data = "Please Press a Button on Your Remote\n";
  29.  
  30. void handleRoot() {
  31.   server.send(200, "text/html", String(data));
  32. }
  33.  
  34.  
  35. void handleNotFound(){
  36.   String message = "File Not Found\n\n";
  37.   message += "URI: ";
  38.   message += server.uri();
  39.   message += "\nMethod: ";
  40.   message += (server.method() == HTTP_GET)?"GET":"POST";
  41.   message += "\nArguments: ";
  42.   message += server.args();
  43.   message += "\n";
  44.   for (uint8_t i=0; i<server.args(); i++){
  45.     message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  46.   }
  47.   server.send(404, "text/plain", message);
  48. }
  49.  
  50. // ==================== start of TUNEABLE PARAMETERS ====================
  51. // An IR detector/demodulator is connected to GPIO pin 14
  52. // e.g. D5 on a NodeMCU board.
  53. // Note: GPIO 16 won't work on the ESP8266 as it does not have interrupts.
  54. // Note: GPIO 14 won't work on the ESP32-C3 as it causes the board to reboot.
  55. #ifdef ARDUINO_ESP32C3_DEV
  56. const uint16_t kRecvPin = 10;  // 14 on a ESP32-C3 causes a boot loop.
  57. #else  // ARDUINO_ESP32C3_DEV
  58. const uint16_t kRecvPin = 14; // pin 14 is D5 on wemos ESP
  59. #endif  // ARDUINO_ESP32C3_DEV
  60.  
  61. // The Serial connection baud rate.
  62. // i.e. Status message will be sent to the PC at this baud rate.
  63. // Try to avoid slow speeds like 9600, as you will miss messages and
  64. // cause other problems. 115200 (or faster) is recommended.
  65. // NOTE: Make sure you set your Serial Monitor to the same speed.
  66. const uint32_t kBaudRate = 115200;
  67.  
  68. // As this program is a special purpose capture/decoder, let us use a larger
  69. // than normal buffer so we can handle Air Conditioner remote codes.
  70. const uint16_t kCaptureBufferSize = 1024;
  71.  
  72. // kTimeout is the Nr. of milli-Seconds of no-more-data before we consider a
  73. // message ended.
  74. // This parameter is an interesting trade-off. The longer the timeout, the more
  75. // complex a message it can capture. e.g. Some device protocols will send
  76. // multiple message packets in quick succession, like Air Conditioner remotes.
  77. // Air Coniditioner protocols often have a considerable gap (20-40+ms) between
  78. // packets.
  79. // The downside of a large timeout value is a lot of less complex protocols
  80. // send multiple messages when the remote's button is held down. The gap between
  81. // them is often also around 20+ms. This can result in the raw data be 2-3+
  82. // times larger than needed as it has captured 2-3+ messages in a single
  83. // capture. Setting a low timeout value can resolve this.
  84. // So, choosing the best kTimeout value for your use particular case is
  85. // quite nuanced. Good luck and happy hunting.
  86. // NOTE: Don't exceed kMaxTimeoutMs. Typically 130ms.
  87. #if DECODE_AC
  88. // Some A/C units have gaps in their protocols of ~40ms. e.g. Kelvinator
  89. // A value this large may swallow repeats of some protocols
  90. const uint8_t kTimeout = 50;
  91. #else   // DECODE_AC
  92. // Suits most messages, while not swallowing many repeats.
  93. const uint8_t kTimeout = 15;
  94. #endif  // DECODE_AC
  95. // Alternatives:
  96. // const uint8_t kTimeout = 90;
  97. // Suits messages with big gaps like XMP-1 & some aircon units, but can
  98. // accidentally swallow repeated messages in the rawData[] output.
  99. //
  100. // const uint8_t kTimeout = kMaxTimeoutMs;
  101. // This will set it to our currently allowed maximum.
  102. // Values this high are problematic because it is roughly the typical boundary
  103. // where most messages repeat.
  104. // e.g. It will stop decoding a message and start sending it to serial at
  105. //      precisely the time when the next message is likely to be transmitted,
  106. //      and may miss it.
  107.  
  108. // Set the smallest sized "UNKNOWN" message packets we actually care about.
  109. // This value helps reduce the false-positive detection rate of IR background
  110. // noise as real messages. The chances of background IR noise getting detected
  111. // as a message increases with the length of the kTimeout value. (See above)
  112. // The downside of setting this message too large is you can miss some valid
  113. // short messages for protocols that this library doesn't yet decode.
  114. //
  115. // Set higher if you get lots of random short UNKNOWN messages when nothing
  116. // should be sending a message.
  117. // Set lower if you are sure your setup is working, but it doesn't see messages
  118. // from your device. (e.g. Other IR remotes work.)
  119. // NOTE: Set this value very high to effectively turn off UNKNOWN detection.
  120. const uint16_t kMinUnknownSize = 12;
  121.  
  122. // How much percentage lee way do we give to incoming signals in order to match
  123. // it?
  124. // e.g. +/- 25% (default) to an expected value of 500 would mean matching a
  125. //      value between 375 & 625 inclusive.
  126. // Note: Default is 25(%). Going to a value >= 50(%) will cause some protocols
  127. //       to no longer match correctly. In normal situations you probably do not
  128. //       need to adjust this value. Typically that's when the library detects
  129. //       your remote's message some of the time, but not all of the time.
  130. const uint8_t kTolerancePercentage = kTolerance;  // kTolerance is normally 25%
  131.  
  132. // Legacy (No longer supported!)
  133. //
  134. // Change to `true` if you miss/need the old "Raw Timing[]" display.
  135. #define LEGACY_TIMING_INFO false
  136. // ==================== end of TUNEABLE PARAMETERS ====================
  137.  
  138. // Use turn on the save buffer feature for more complete capture coverage.
  139. IRrecv irrecv(kRecvPin, kCaptureBufferSize, kTimeout, true);
  140. decode_results results;  // Somewhere to store the results
  141.  
  142. // This section of code runs only once at start-up.
  143. void setup() {
  144. #if defined(ESP8266)
  145.   Serial.begin(kBaudRate, SERIAL_8N1, SERIAL_TX_ONLY);
  146. #else  // ESP8266
  147.   Serial.begin(kBaudRate, SERIAL_8N1);
  148. #endif  // ESP8266
  149.   while (!Serial)  // Wait for the serial connection to be establised.
  150.     delay(50);
  151.   // Perform a low level sanity checks that the compiler performs bit field
  152.   // packing as we expect and Endianness is as we expect.
  153.   assert(irutils::lowLevelSanityCheck() == 0);
  154.  
  155.   Serial.printf("\n" D_STR_IRRECVDUMP_STARTUP "\n", kRecvPin);
  156. #if DECODE_HASH
  157.   // Ignore messages with less than minimum on or off pulses.
  158.   irrecv.setUnknownThreshold(kMinUnknownSize);
  159. #endif  // DECODE_HASH
  160.   irrecv.setTolerance(kTolerancePercentage);  // Override the default tolerance.
  161.   irrecv.enableIRIn();  // Start the receiver
  162.  
  163.  ///WiFi Manager Setup///
  164.      WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
  165.     // it is a good practice to make sure your code sets wifi mode how you want it.
  166.  
  167.     // put your setup code here, to run once:
  168.    
  169.     //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around
  170.     WiFiManager wm;
  171.  
  172.     // reset settings - wipe stored credentials for testing
  173.     // these are stored by the esp library
  174.     //wm.resetSettings();
  175.  
  176.     // Automatically connect using saved credentials,
  177.     // if connection fails, it starts an access point with the specified name ( "AutoConnectAP"),
  178.     // if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect())
  179.     // then goes into a blocking loop awaiting configuration and will return success result
  180.  
  181.     bool res;
  182.     // res = wm.autoConnect(); // auto generated AP name from chipid
  183.     res = wm.autoConnect("IR_ESP"); // anonymous ap
  184.     //res = wm.autoConnect("AutoConnectAP","password"); // password protected ap
  185.  
  186.     if(!res) {
  187.         Serial.println("Failed to connect");
  188.         // ESP.restart();
  189.     }
  190.     else {
  191.         //if you get here you have connected to the WiFi    
  192.         Serial.println("connected...yeey :)");
  193.     }
  194.  
  195.     ///webserver setup///
  196.   server.on("/", handleRoot);
  197.  
  198.   server.on("/inline", [](){
  199.     server.send(200, "text/plain", "this works as well");
  200.   });
  201.  
  202.   server.onNotFound(handleNotFound);
  203.  
  204.   server.begin();
  205. }
  206.  
  207. // The repeating section of the code
  208. void loop() {
  209.   // Check if the IR code has been received.
  210.   if (irrecv.decode(&results)) {
  211.  
  212.     // Display a crude timestamp.
  213.     uint32_t now = millis();
  214.     Serial.printf(D_STR_TIMESTAMP " : %06u.%03u\n", now / 1000, now % 1000);
  215.     // Check if we got an IR message that was to big for our capture buffer.
  216.     if (results.overflow)
  217.       Serial.printf(D_WARN_BUFFERFULL "\n", kCaptureBufferSize);
  218.     // Display the library version the message was captured with.
  219.     Serial.println(D_STR_LIBRARY "   : v" _IRREMOTEESP8266_VERSION_STR "\n");
  220.     // Display the tolerance percentage if it has been change from the default.
  221.     if (kTolerancePercentage != kTolerance)
  222.       Serial.printf(D_STR_TOLERANCE " : %d%%\n", kTolerancePercentage);
  223.     // Display the basic output of what we found.
  224.     Serial.print(resultToHumanReadableBasic(&results));
  225.     // Display any extra A/C info if we have it.
  226.     String description = IRAcUtils::resultAcToString(&results);
  227.     if (description.length()) Serial.println(D_STR_MESGDESC ": " + description);
  228.     yield();  // Feed the WDT as the text output can take a while to print.
  229. #if LEGACY_TIMING_INFO
  230.     // Output legacy RAW timing info of the result.
  231.     Serial.println(resultToTimingInfo(&results));
  232.     yield();  // Feed the WDT (again)
  233. #endif  // LEGACY_TIMING_INFO
  234.     // Output the results as source code
  235.     Serial.println(resultToSourceCode(&results));
  236.     data+="<pre>";
  237.     data+=resultToSourceCode(&results);
  238.     data+="</pre>\n";
  239.     data+="<script>setTimeout(location.reload.bind(location), 1000);</script>";
  240.     Serial.println();    // Blank line between entries
  241.     yield();             // Feed the WDT (again)
  242.   }
  243.   server.handleClient();
  244. }
Add Comment
Please, Sign In to add comment