創作內容

10 GP

ESP8266 WiFi 整合Arduino MEGA2560 實現遠端控制

作者:貓貓風 ฅ●ω●ฅ│2022-11-14 14:44:42│巴幣:23│人氣:1515
.













控制架構




ESP8266 與 Arduino 使用 UART進行資料傳輸 (ESP8266用來收發資料)

手機端主要用來連接 ESP8266用來遠端操控

MEGA2560的IO接出兩個LED,當收到開關指令會做出對應的動作

正統的做法其實是將ESP8266連接到固定熱點,然後手機也連接到那個熱點進行遠端操控

但目前手邊沒有固定的熱點可以用   才用手機代替


ESP8266前置設定可以參考這篇



程式主要分為兩部分

由於ESP8266與MEGA2560是兩個獨立的MCU,因此程式要個別撰寫

上圖雖然兩者是疊在一起,程式要用兩個不同的COMPORT進行燒寫

ESP8266是用CH340使用ARDUINO IDE進行燒寫

MEGA2560是用自帶的USB使用ARDUINO IDE進行燒寫

ESP8266與MEGA2560使用的是自定義的通訊協定




ESP8266


  1. // Load Wi-Fi library
  2. #include <ESP8266WiFi.h>
  3. #include <SoftwareSerial.h>
  4. // Replace with your network credentials
  5. const char* ssid     = "SSID";
  6. const char* password = "PWD";
  7. // Set web server port number to 80
  8. WiFiServer server(80);
  9. // Variable to store the HTTP request
  10. String header;
  11. // Auxiliar variables to store the current output state
  12. String output13State = "off";
  13. String output12State = "off";
  14. // Assign output variables to GPIO pins
  15. const int output13 = 13;
  16. const int output12 = 12;
  17. // Current time
  18. unsigned long currentTime = millis();
  19. // Previous time
  20. unsigned long previousTime = 0;
  21. // Define timeout time in milliseconds (example: 2000ms = 2s)
  22. const long timeoutTime = 2000;
  23. const byte rxPin = 4;
  24. const byte txPin = 5;
  25. String send_packet = "";
  26. SoftwareSerial Ext_Serial (rxPin, txPin);
  27. void setup() {
  28.   Ext_Serial.begin(9600);
  29.   Serial.begin(115200);
  30.   // Initialize the output variables as outputs
  31.   pinMode(output13, OUTPUT);
  32.   pinMode(output12, OUTPUT);
  33.   // Set outputs to LOW
  34.   digitalWrite(output13, LOW);
  35.   digitalWrite(output12, LOW);
  36.   // Connect to Wi-Fi network with SSID and password
  37.   Serial.print("Connecting to ");
  38.   Serial.println(ssid);
  39.   WiFi.begin(ssid, password);
  40.   while (WiFi.status() != WL_CONNECTED) {
  41.     delay(500);
  42.     Serial.print(".");
  43.   }
  44.   // Print local IP address and start web server
  45.   Serial.println("");
  46.   Serial.println("WiFi connected.");
  47.   Serial.println("IP address: ");
  48.   Serial.println(WiFi.localIP());
  49.   server.begin();
  50. }
  51. int connect_count = 0;
  52. void loop(){
  53.   WiFiClient client = server.available();   // Listen for incoming clients
  54.   if (client) {                             // If a new client connects,
  55.     Serial.println("New Client.");          // print a message out in the serial port
  56.     String currentLine = "";                // make a String to hold data from the client
  57.     currentTime = millis();
  58.     previousTime = currentTime;
  59.     while (client.connected() && currentTime - previousTime <= timeoutTime) {
  60.       currentTime = millis();         
  61.       if (client.available()) {             // if there's bytes to read from the client,
  62.         char c = client.read();             // read a byte, then
  63.         Serial.write(c);                    // print it out the serial monitor
  64.         header += c;
  65.         if (c == '\n') {                    // if the byte is a newline character
  66.           // if the current line is blank, you got two newline characters in a row.
  67.           // that's the end of the client HTTP request, so send a response:
  68.           if (currentLine.length() == 0) {
  69.             // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
  70.             // and a content-type so the client knows what's coming, then a blank line:
  71.             client.println("HTTP/1.1 200 OK");
  72.             client.println("Content-type:text/html");
  73.             client.println("Connection: close");
  74.             client.println();
  75.             
  76.             // turns the GPIOs on and off
  77.             if (header.indexOf("GET /13/on") >= 0) {
  78.               Serial.println("GPIO 13 on");
  79.               //Ext_Serial.write("GPIO 13 on");
  80.               output13State = "on";
  81.               digitalWrite(output13, HIGH);
  82.               //==============================
  83.               String send_packet = "s00GIOSD1\r";
  84.               byte packet[send_packet.length()];
  85.               send_packet.getBytes(packet, 10);
  86.               Ext_Serial.write(packet,10);
  87.               //===============================
  88.             } else if (header.indexOf("GET /13/off") >= 0) {
  89.               Serial.println("GPIO 13 off");
  90.               output13State = "off";
  91.               digitalWrite(output13, LOW);
  92.               //==============================
  93.               String send_packet = "s00GIOSD0\r";
  94.               byte packet[send_packet.length()];
  95.               send_packet.getBytes(packet, 10);
  96.               Ext_Serial.write(packet,10);
  97.               //===============================
  98.             } else if (header.indexOf("GET /12/on") >= 0) {
  99.               Serial.println("GPIO 12 on");
  100.               //Ext_Serial.write("GPIO 12 on");
  101.               output12State = "on";
  102.               digitalWrite(output12, HIGH);
  103.               //==============================
  104.               String send_packet = "s00GIOSC1\r";
  105.               byte packet[send_packet.length()];
  106.               send_packet.getBytes(packet, 10);
  107.               Ext_Serial.write(packet,10);
  108.               //===============================
  109.             } else if (header.indexOf("GET /12/off") >= 0) {
  110.               Serial.println("GPIO 12 off");
  111.               //Ext_Serial.write("GPIO 12 off");
  112.               output12State = "off";
  113.               digitalWrite(output12, LOW);
  114.                 //==============================
  115.               String send_packet = "s00GIOSC0\r";
  116.               byte packet[send_packet.length()];
  117.               send_packet.getBytes(packet, 10);
  118.               Ext_Serial.write(packet,10);
  119.               //===============================
  120.             }
  121.             
  122.             // Display the HTML web page
  123.             client.println("<!DOCTYPE html><html>");
  124.             client.println("<head><meta name=\"viewport\" content=\"width=device-width,
  125.             initial-scale=1\">");
  126.             client.println("<link rel=\"icon\" href=\"data:,\">");
  127.             // CSS to style the on/off buttons
  128.             client.println("<style>html { font-family: Helvetica; display: inline-block;
  129.             margin: 0px auto; text-align: center;}");
  130.             client.println(".button { background-color: #195B6A; border: none; color:
  131.             white; padding: 16px 40px; margin-left:5px;");
  132.             client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor:
  133.             pointer;}");
  134.             client.println(".button2 {background-color: #77878A;}</style></head>");
  135.             
  136.             // Web Page Heading
  137.             client.println("<body
  138.             background=\"https://img2.huashi6.com/images/resource
  139.             /fhlt83f4plfqebsxlduklafeqm1m.jpg?imageView2/3/q/75
  140.             /interlace/1/w/600/h/600\"><p style=\"color:blue\">
  141.             <h1>ESP8266 Web Server</h1></p>");
  142.             
  143.             // Display current state, and ON/OFF buttons for GPIO 13  
  144.             client.println("<p style=\"color:blue\">GPIO 13 - State " + output13State + "
  145.             </p>");
  146.             // If the output13State is off, it displays the ON button       
  147.             if (output13State=="off") {
  148.               client.println("<p><a href=\"/13/on\"><button class=\"button\">ON</button>
  149.               </a></p>");
  150.             } else {
  151.               client.println("<p><a href=\"/13/off\"><button class=\"button
  152.               button2\">OFF</button></a></p>");
  153.             }
  154.                
  155.             // Display current state, and ON/OFF buttons for GPIO 12
  156.             client.println("<p style=\"color:blue\">GPIO 12 - State " + output12State + "
  157.             </p>");
  158.             // If the output12State is off, it displays the ON button       
  159.             if (output12State=="off") {
  160.               client.println("<p><a href=\"/12/on\"><button class=\"button\">ON</button>
  161.               </a></p>");
  162.             } else {
  163.               client.println("<p><a href=\"/12/off\"><button class=\"button
  164.               button2\">OFF</button></a></p>");
  165.             }
  166.             connect_count++;
  167.             client.println("<p style=\"color:blue\"><font size=\"5\">Query
  168.             Count:"+String("")+connect_count+"</font></p>");
  169.             client.println("</body></html>");
  170.             
  171.             // The HTTP response ends with another blank line
  172.             client.println();
  173.             // Break out of the while loop
  174.             break;
  175.           } else { // if you got a newline, then clear currentLine
  176.             currentLine = "";
  177.           }
  178.         } else if (c != '\r') {  
  179.           currentLine += c;      // add it to the end of the currentLine
  180.         }
  181.       }
  182.     }
  183.     // Clear the header variable
  184.     header = "";
  185.     // Close the connection
  186.     client.stop();
  187.     Serial.println("Client disconnected.");
  188.     Serial.println("");
  189.   }
  190. }

MEGA2560


  1. String ASCII_table[] = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
  2. void setup() {
  3.   // put your setup code here, to run once:
  4.   Serial.begin(9600);
  5.   Serial3.begin(9600);
  6.   pinMode(12,OUTPUT);
  7.   pinMode(13,OUTPUT);
  8. }
  9. int rev_idx = 0;
  10. byte rev_packet[10];
  11. void loop() {
  12.   // put your main code here, to run repeatedly:
  13.     if(Serial3.available())
  14.     {
  15.        byte rev_data = Serial3.read();
  16.        rev_packet[rev_idx] = rev_data;
  17.        rev_idx ++;
  18.        if((char)rev_data == '\r' || rev_idx>= 10)
  19.        {
  20.           byte byteArray[10];
  21.           String decode_String = String((char*)rev_packet);
  22.           Serial.println(decode_String);
  23.           String io_dot = decode_String.substring(7,8);
  24.            //Serial.println(io_dot);
  25.           int trigger_dot = 0;
  26.           for(int i = 0 ; i <= 15 ; i++ )
  27.           {
  28.             if(io_dot == ASCII_table[i])
  29.             {
  30.               trigger_dot = i;
  31.               break;
  32.             }
  33.           }
  34.           String on_off = decode_String.substring(8,9);
  35.           String on_state = "";
  36.           if(on_off == "1")
  37.           {
  38.             on_state = "ON";
  39.             digitalWrite(trigger_dot,HIGH);
  40.           }
  41.           else
  42.           {
  43.             on_state = "OFF";
  44.             digitalWrite(trigger_dot,LOW);
  45.           }
  46.            Serial.println(String()+"IO "+trigger_dot + " is "+ on_state);
  47.           rev_idx = 0;
  48.        }
  49.     }
  50. }

執行結果

預設兩個LED都是關閉


使用按鍵遠端發送指令  將其中一顆 LED點亮

使用按鍵遠端發送指令  將另外一顆 LED點亮




引用網址:https://home.gamer.com.tw/TrackBack.php?sn=5600762
All rights reserved. 版權所有,保留一切權利

相關創作

同標籤作品搜尋:ESP8266|Aduino|WiFi|MEGA2560

留言共 0 篇留言

我要留言提醒:您尚未登入,請先登入再留言

10喜歡★s1234567 可決定是否刪除您的留言,請勿發表違反站規文字。

前一篇:ESP8266 wifi... 後一篇:ESP8266 WEB ...

追蹤私訊切換新版閱覽

作品資料夾

Lobster0627全體巴友
大家可以多多來我的YT頻道看看哦(*´∀`)~♥https://www.youtube.com/@lobstersandwich看更多我要大聲說昨天18:56


face基於日前微軟官方表示 Internet Explorer 不再支援新的網路標準,可能無法使用新的應用程式來呈現網站內容,在瀏覽器支援度及網站安全性的雙重考量下,為了讓巴友們有更好的使用體驗,巴哈姆特即將於 2019年9月2日 停止支援 Internet Explorer 瀏覽器的頁面呈現和功能。
屆時建議您使用下述瀏覽器來瀏覽巴哈姆特:
。Google Chrome(推薦)
。Mozilla Firefox
。Microsoft Edge(Windows10以上的作業系統版本才可使用)

face我們了解您不想看到廣告的心情⋯ 若您願意支持巴哈姆特永續經營,請將 gamer.com.tw 加入廣告阻擋工具的白名單中,謝謝 !【教學】