Các dự án ứng dụng lập trình IOT với ESP8266 trong Arduino

75 1.2K 12
Các dự án ứng dụng lập trình IOT với  ESP8266 trong Arduino

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chuẩn bị: Cài đặt ESP8266 để lập trình trong Arduino.Dự án 1: Lập trình đồng hồ LED 7 đoạn dùng ESP8266 và DS1307Dự án 2: Điều khiển ESP8266 bằng giọng nói với Google AssistantDự án 3 Giải mã dữ liệu thời tiết qua cấu trúc JSON trong ArduinoDự án 4 WiFiManager cho ESP8266 – tự động kết nối, cấu hình, quản lý SSID và Password

Bốn dự án ứng dụng lập trình IOT với ESP8266 Arduino Mục lục Giới thiệu Chuẩn bị: Cài đặt ESP8266 để lập trình Arduino Dự án 1: Lập trình đồng hồ LED đoạn dùng ESP8266 DS1307 10 Dự án 2: Điều khiển ESP8266 giọng nói với Google Assistant 31 Dự án - Giải mã liệu thời tiết qua cấu trúc JSON Arduino 38 Dự án - WiFiManager cho ESP8266 – tự động kết nối, cấu hình, quản lý SSID Password 53 Giới thiệu ESP8266 tương đối phổ thơng Việt Nam chi phí không cao Trong tài liệu này, giới thiệu dự án tơi lập trình với ESP8266 cho bạn tham khảo Cơng cụ dùng để lập trình Arduino IDE Chuẩn bị: Cài đặt ESP8266 để lập trình Arduino NodeMCU bo mạch khai thác khả chip esp8266 Nó kết hợp chức WIFI, vi xử lý ngôn ngữ LUA ESP8266 NodeMCU cung cấp      Giống chân IO phần cứng Arduino API điền khiển kiện cho ứng dụng mạng 10 chân GPIO từ D0 – D10, có chức PWM, IIC, giao tiếp SPI, 1-Wire ADC chân A0 Kết nối mạng wifi (có thể sử dụng điểm truy cập và/hoặc trạm máy chủ lưu trữ một, máy chủ web), kết nối internet để lấy tải lên liệu Chi phí phù hợp cho dự án Internet of Things (IoT) PHẦN CỨNG Module ESP8266 1) Cài Arduino dành cho chip ESP8266 WiFi Arduino IDE xem code mẫu 2) Chạy chỉnh sửa code mẫu để kiểm tra chân D0 , GPIO-16 chân cấu hình Ghi – để sử dụng bo mạch NodeMCU V1 V2 V3 Arduino IDE, bạn không cần chép firmware với cơng cụ using nodemcu flasher Nó u cầu sử dụng ngơn ngữ LUA Bạn theo dõi video hướng dẫn chép firware sau: Bước 1: Lập sơ đồ chân NodeMCU ESP-12E * Chip ESP8266 sử dụng điện áp 3.3V , bạn lấy mức điện áp từ bo Arduino * NodeMCU ESP-12E nối với nguồn 5V sử dụng cáp micro USB chân Vin có sẵn bo * Các chân ESP8266 sử dụng điện áp 3.3V , không sử dụng điện áp 5V chân ngõ vào Khi sử dụng với chân I/O 5V, bạn cần sử dụng mạch chuyển đổi từ 5V sang 3.3V Tải : source of images https://github.com/nodemcu/nodemcu-devkit * Github – NodeMCU https://github.com/nodemcu/nodemcu-devkit-v1.0 * Github-esp8266/ Arduino https://github.com/esp8266/Arduino/issues/584 Bước 2: cài đặt chương trình lõi Arduino cho NodeMCU ESP-12E dùng chương trình quản lý bo Arduino Chép đường link sau từ trang Github http://arduino.esp8266.com/stable/package_esp8266com_index.json Dán link vào Arduino IDE File -> PreferencesĐóng khởi động lại Arduino IDE Bước : Tools – Boards Manager Vào Tools – Boards manager tìm ESP8266 cài đặt thư viện có tiêu đề ESP8266 by ESP community Khởi động Arduino IDE lại lần Bước 4: chọn NodeMCU Board Arduino IDE Vào Tools – Boards kéo xuống cuối danh sách chọn NodeMCU 1.0 ( ESP-12EModule) Chọn tên Port kết nối tới nodeMCU, phần lại để mặc định Bước 5: LED Blink – kết nối với led bên Chúng nối LED trực tiếp vào chân GPIO16 D0 NodeMCU (khơng cần điện trở hạn dòng) Bước 6: chạy ví dụ LED Blink Vào File – Examples – ESP8266 – Blink Trong video sửa lại để LED nháy nhanh hơn, bạn bỏ qua up mã nguồn vào ESP xem kết Ghi chú: Nếu Arduino IDE 1.6.7 bị lỗi bạn trở lại arduino 1.6.5 Dự án 1: Lập trình đồng hồ LED đoạn dùng ESP8266 DS1307 Trên thị trường có bán sẵn đồng hồ LED đoạn dùng chip thời gian thực, kích thước đồng hồ đa số nhỏ Trong dự án này, tơi làm đồng hồ dùng LED đoạn loại lớn để hiển thị thời gian Điểm đặc thù đồng hồ dùng chip wifi ESP8266 để tự động cập nhật thời gian từ internet, sau lưu thơng tin thời gian vào DS1307 hiển thị lên LED đoạn Ưu điểm   Cập nhật thời gian thực từ Internet Loại bỏ phím nhấn vật lý Linh kiện phần cứng 10 11 12 LED đoạn loại lớn sử dụng nguồn dương chung Module wifi ESP8266 nodeMCU Module đồng hồ thời gian thực DS1307 tương đương Pin CMOS dùng cho module đồng hồ IC 74HC595 + đế cho IC Mạch giảm áp DC mini bóng đèn LED làm nháy giây Trong dự án sử dụng bóng LED 5050 RGB có sẵn kho linh kiện Bo mạch thí nghiệm để gắn linh kiện Điện trở 1K Transistor A1015 điện trở 330ohm Nguồn 5VDC Chọn mạng muốn kết nối, tự lấy thơng tin mạng cho bạn (Ví dụ “MEO-620B4B”): Sau nhập mật nhấn “save“ Bạn thấy thông báo sau: Serial Monitor hiển thị kết dò tìm Access Point thơng tin trạng thái lưu Truy cập web server Nhấn nút RESET bo ESP để khởi động lại module, địa hiển Serial Monitor (ví dụ 192.168.1.132): Bạn mở trình duyện vào gõ IP vào Bạn thấy trang web hiển thị đây, cho phép bạn điều khiển GPIO Linh kiện cần có ESP8266 2x LED 2x điện trở (220 330 ohms) Breadboard Sơ đồ kết nối: Làm để xóa thơng tin mạng wifi ESP8266 Sử dụng câu lệnh sau: wifiManager.resetSettings(); Ví dụ #2 – WiFiManager với ESP8266 cấu hình thơng số Thư viện WiFiManager có chức hữu dụng cho phép bạn thêm tham số “Configure WiFi” Nó hữu ích, số ứng dụng cần thêm giá trị API Key, MQTT broker IP Address, gán GPIO khác, kích hoạt cảm biến, etc Mã nguồn /********* Rui Santos Complete project details at http://randomnerdtutorials.com *********/ #include //this needs to be first, or it all crashes and burns #include #include #include #include // https://github.com/tzapu/WiFiManager #include // https://github.com/bblanchon/ArduinoJson // Set web server port number to 80 WiFiServer server(80); // Variable to store the HTTP request String header; // Auxiliar variables to store the current output state String outputState = "off"; // Assign output variables to GPIO pins char output[2] = "5"; //flag for saving data bool shouldSaveConfig = false; //callback notifying us of the need to save config void saveConfigCallback () { Serial.println("Should save config"); shouldSaveConfig = true; } void setup() { Serial.begin(115200); //clean FS, for testing //SPIFFS.format(); //read configuration from FS json Serial.println("mounting FS "); if (SPIFFS.begin()) { Serial.println("mounted file system"); if (SPIFFS.exists("/config.json")) { //file exists, reading and loading Serial.println("reading config file"); File configFile = SPIFFS.open("/config.json", "r"); if (configFile) { Serial.println("opened config file"); size_t size = configFile.size(); // Allocate a buffer to store contents of the file std::unique_ptr buf(new char[size]); configFile.readBytes(buf.get(), size); DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); if (json.success()) { Serial.println("\nparsed json"); strcpy(output, json["output"]); } else { Serial.println("failed to load json config"); } } } } else { Serial.println("failed to mount FS"); } //end read WiFiManagerParameter custom_output("output", "output", output, 2); // WiFiManager // Local intialization Once its business is done, there is no need to keep it around WiFiManager wifiManager; //set config save notify callback wifiManager.setSaveConfigCallback(saveConfigCallback); // set custom ip for portal //wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); //add all your parameters here wifiManager.addParameter(&custom_output); // Uncomment and run it once, if you want to erase all the stored information //wifiManager.resetSettings(); //set minimu quality of signal so it ignores AP's under that quality //defaults to 8% //wifiManager.setMinimumSignalQuality(); //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds //wifiManager.setTimeout(120); // fetches ssid and pass from eeprom and tries to connect // if it does not connect it starts an access point with the specified name // here "AutoConnectAP" // and goes into a blocking loop awaiting configuration wifiManager.autoConnect("AutoConnectAP"); // or use this for auto generated name ESP + ChipID //wifiManager.autoConnect(); // if you get here you have connected to the WiFi Serial.println("Connected."); strcpy(output, custom_output.getValue()); //save the custom parameters to FS if (shouldSaveConfig) { Serial.println("saving config"); DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["output"] = output; File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { Serial.println("failed to open config file for writing"); } json.printTo(Serial); json.printTo(configFile); configFile.close(); //end save } // Initialize the output variables as outputs pinMode(atoi(output), OUTPUT); // Set outputs to LOW digitalWrite(atoi(output), LOW);; server.begin(); } void loop(){ WiFiClient client = server.available(); // Listen for incoming clients if (client) { // If a new client connects, Serial.println("New Client."); serial port // print a message out in the String currentLine = ""; data from the client // make a String to hold incoming while (client.connected()) { connected // loop while the client's if (client.available()) { the client, // if there's bytes to read from char c = client.read(); // read a byte, then Serial.write(c); // print it out the serial monitor header += c; if (c == '\n') { character // if the byte is a newline // if the current line is blank, you got two newline characters in a row // that's the end of the client HTTP request, so send a response: if (currentLine.length() == 0) { // HTTP headers always start with a response code (e.g HTTP/1.1 200 OK) // and a content-type so the client knows what's coming, then a blank line: client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println("Connection: close"); client.println(); // turns the GPIOs on and off if (header.indexOf("GET /output/on") >= 0) { Serial.println("Output on"); outputState = "on"; digitalWrite(atoi(output), HIGH); } else if (header.indexOf("GET /output/off") >= 0) { Serial.println("Output off"); outputState = "off"; digitalWrite(atoi(output), LOW); } // Display the HTML web page client.println(""); client.println(""); client.println(""); // CSS to style the on/off buttons // Feel free to change the background-color and font-size attributes to fit your preferences client.println("html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}"); client.println(".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;"); client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}"); client.println(".button2 {background-color: #77878A;}"); // Web Page Heading client.println("ESP8266 Web Server"); // Display current state, and ON/OFF buttons for the defined GPIO client.println("

Output - State " + outputState + "

"); // If the outputState is off, it displays the ON button if (outputState=="off") { client.println("

ON

"); } else { client.println("

OFF

"); } client.println(""); // The HTTP response ends with another blank line client.println(); // Break out of the while loop break; } else { // if you got a newline, then clear currentLine currentLine = ""; } } else if (c != '\r') { return character, currentLine += c; // if you got anything else but a carriage // add it to the end of the currentLine } } } // Clear the header variable header = ""; // Close the connection client.stop(); Serial.println("Client disconnected."); Serial.println(""); } Tạo thêm tham số Để thêm tham số, bạn cần thao tác tập tin config.json lưu ESP Bài nàu không giải thích làm làm việc với tham số thêm vào, bản, bạn muốn tạo thêm tham số, bạn cần làm theo bước sau đây: Trongdụ này, tạo biến để lưu địa IP MQTT broker server char output[2]; char mqtt_server[40]; Sau đó, lưu file /config.json, bạn chép nó: strcpy(output, json["output"]); strcpy(mqtt_server, json["mqtt_server"]); Tạo WiFiManagerParameter (tham số hiển thị “Configure WiFi” ): WiFiManagerParameter custom_output("output", "output", output, 2); WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); Thêm biến tham số: wifiManager.addParameter(&custom_output); wifiManager.addParameter(&custom_mqtt_server); Kiểm tra cập nhật biến với giá trị nhất: strcpy(output, custom_output.getValue()); strcpy(mqtt_server, custom_mqtt_server.getValue()); Cuối cùng, người dùng tạo giá trị vào tham số, cập nhật vào file config.json : strcpy(output, custom_output.getValue()); strcpy(mqtt_server, custom_mqtt_server.getValue()); Bạn lập lại việc để thêm tham số Truy cập WiFiManager AP Sử dụng điện thoại, máy tính, máy tính bảng kết nối vào AutoConnectAP Access Point: Bạn thấy cửa sổ tương tự hình bên nhấn nút “SIGN IN” : Trang cấu hình WiFi Bạn truy cập địa 192.168.4.để cấu hình WiFi , nhấn nút “Configure WiFi” : Chọn mạng cần kết nối (ví dụ “MEO-620B4B”): Sau nhập mật khẩu, nhập số GPIO (ví dụ GPIO nhập số 5) nhấn “save“: Quan sát Serial Monitor :    Qt tìm kiếm Access Point; Thơng tin trạng thái Wi-Fi lưu lại; Xác nhận thông số ngõ (ví dụ GPIO5): {“output”:”5″} Truy cập web server Bây bạn RESET mạch ESP, se in địa IP Serial Monitor (ví dụ 192.168.1.132): Mở trình duyệt, nhập địa IP Bạn thấy trang web bên dưới, cho phép bạn điều khiển chân GPIO mà bạn định nghĩa dạng tắt mở: Linh kiện sơ đồ ESP8266 12-E 1x LED 1x Resistor (220 or 330 ohms should work just fine) Breadboard Ghi chú; Nếu bạn định nghĩa chân khác với chân GPIO (là chân D1 module NodeMCU), bạn cần làm lại phần cứng

Ngày đăng: 30/03/2018, 15:26

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan