ESP8266 http收發數據

1.先修改基礎配置?

make menuconfig

打開配置菜單

選擇component config?

然后選擇

?修改波特率為115200

保存退出?

2.修改彩色日志打印的

在component config目錄下找到log output

?選中點擊空格關掉彩色日志輸出,這樣正常串口打印就沒有亂碼了

然后保存退出

3.串口接收json,http發送云代碼

設備 HTTP 接入 | ThingsCloud 使用文檔

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_http_client.h"
#include "cJSON.h"
#include <stdio.h>
#include <string.h>#define LED_GPIO 2
#define PROJECT_KEY "*"char g_wifi_ssid[64] = "";
char g_wifi_pass[64] = "";
char g_post_json[512] = "";SemaphoreHandle_t xPostSemaphore;// WiFi Event Handler
esp_err_t event_handler(void *ctx, system_event_t *event)
{switch (event->event_id){case SYSTEM_EVENT_STA_START:esp_wifi_connect();break;case SYSTEM_EVENT_STA_GOT_IP:printf("Got IP: %s\n", ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));break;case SYSTEM_EVENT_STA_DISCONNECTED:printf("Disconnected, retrying...\n");esp_wifi_connect();break;default:break;}return ESP_OK;
}// init once
void wifi_driver_init()
{tcpip_adapter_init();ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();ESP_ERROR_CHECK(esp_wifi_init(&cfg));ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));ESP_ERROR_CHECK(esp_wifi_start());
}//  change WiFi connect
void wifi_connect()
{wifi_config_t wifi_config = {0};strcpy((char *)wifi_config.sta.ssid, g_wifi_ssid);strcpy((char *)wifi_config.sta.password, g_wifi_pass);// 先斷開esp_wifi_disconnect();vTaskDelay(pdMS_TO_TICKS(100));// 設置新配置ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));// 連接ESP_ERROR_CHECK(esp_wifi_connect());
}// uart receive task
void uart_receive_task(void *pvParams)
{const int uart_num = UART_NUM_0;uart_config_t uart_config = {.baud_rate = 115200,.data_bits = UART_DATA_8_BITS,.parity    = UART_PARITY_DISABLE,.stop_bits = UART_STOP_BITS_1,.flow_ctrl = UART_HW_FLOWCTRL_DISABLE};uart_param_config(uart_num, &uart_config);uart_driver_install(uart_num, 2048, 0, 0, NULL, 0);uint8_t data[512];while (1){int len = uart_read_bytes(uart_num, data, sizeof(data) - 1, pdMS_TO_TICKS(1000));if (len > 0){data[len] = '\0';printf("UART Received: %s\n", data);cJSON *root = cJSON_Parse((char *)data);if (!root){printf("JSON Parse Error\n");}else{cJSON *ssid = cJSON_GetObjectItem(root, "ssid");cJSON *pass = cJSON_GetObjectItem(root, "pass");if (ssid && pass){// WiFi 賬號密碼配置strncpy(g_wifi_ssid, ssid->valuestring, sizeof(g_wifi_ssid) - 1);strncpy(g_wifi_pass, pass->valuestring, sizeof(g_wifi_pass) - 1);printf("Set WiFi SSID: %s\n", g_wifi_ssid);printf("Set WiFi PASS: %s\n", g_wifi_pass);wifi_connect();}else{// 透傳 POST 數據strncpy(g_post_json, (char *)data, sizeof(g_post_json) - 1);g_post_json[sizeof(g_post_json) - 1] = '\0';printf("POST JSON set: %s\n", g_post_json);xSemaphoreGive(xPostSemaphore); // 通知 POST 任務}cJSON_Delete(root);}}}
}// HTTP POST task
void http_post_task(void *pvParameters)
{while (1){if (xSemaphoreTake(xPostSemaphore, portMAX_DELAY) == pdTRUE){esp_http_client_config_t config = {.url = "http://sh-3-api.iot-api.com/device/v1/<*your tocken>/attributes",};esp_http_client_handle_t client = esp_http_client_init(&config);esp_http_client_set_method(client, HTTP_METHOD_POST);esp_http_client_set_header(client, "Content-Type", "application/json");esp_http_client_set_header(client, "Project-Key", PROJECT_KEY);esp_http_client_set_post_field(client, g_post_json, strlen(g_post_json));esp_err_t err = esp_http_client_perform(client);if (err == ESP_OK){printf("HTTP POST Status = %d, content_length = %d\n",esp_http_client_get_status_code(client),esp_http_client_get_content_length(client));}else{printf("HTTP POST request failed: %s\n", esp_err_to_name(err));}esp_http_client_cleanup(client);}}
}// LED task
void led_blink_task(void *pvParams)
{gpio_set_direction(LED_GPIO, GPIO_MODE_OUTPUT);while (1){gpio_set_level(LED_GPIO, 1);vTaskDelay(pdMS_TO_TICKS(500));gpio_set_level(LED_GPIO, 0);vTaskDelay(pdMS_TO_TICKS(500));}
}// Main
void app_main()
{nvs_flash_init();wifi_driver_init();xPostSemaphore = xSemaphoreCreateBinary();xTaskCreate(uart_receive_task, "uart_receive_task", 4096, NULL, 5, NULL);xTaskCreate(http_post_task, "http_post_task", 8192, NULL, 5, NULL);xTaskCreate(led_blink_task, "led_blink_task", 2048, NULL, 5, NULL);
}

4.使用方法

(1)串口接收數據配網(不要有空格)

{"ssid":"***","pass":"********"}

(2)串口接收數據http發送云(不要有空格,數據可以自己往后添加)

{"temperature":115,"humidity":32.2,"switch":true}

5.效果

6.get線程獲取云服務數據(需要修改兩個url的token)

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "driver/uart.h"
#include "driver/gpio.h"
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_http_client.h"
#include "cJSON.h"
#include <stdio.h>
#include <string.h>#define LED_GPIO 2
#define PROJECT_KEY "*"char g_wifi_ssid[64] = "";
char g_wifi_pass[64] = "";
char g_post_json[512] = "";SemaphoreHandle_t xPostSemaphore;// WiFi Event Handler
esp_err_t event_handler(void *ctx, system_event_t *event)
{switch (event->event_id){case SYSTEM_EVENT_STA_START:esp_wifi_connect();break;case SYSTEM_EVENT_STA_GOT_IP:printf("Got IP: %s\n", ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));break;case SYSTEM_EVENT_STA_DISCONNECTED:printf("Disconnected, retrying...\n");esp_wifi_connect();break;default:break;}return ESP_OK;
}// init once
void wifi_driver_init()
{tcpip_adapter_init();ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();ESP_ERROR_CHECK(esp_wifi_init(&cfg));ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));ESP_ERROR_CHECK(esp_wifi_start());
}//  change WiFi connect
void wifi_connect()
{wifi_config_t wifi_config = {0};strcpy((char *)wifi_config.sta.ssid, g_wifi_ssid);strcpy((char *)wifi_config.sta.password, g_wifi_pass);// 先斷開esp_wifi_disconnect();vTaskDelay(pdMS_TO_TICKS(100));// 設置新配置ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));// 連接ESP_ERROR_CHECK(esp_wifi_connect());
}// 串口接收任務
void uart_receive_task(void *pvParams)
{const int uart_num = UART_NUM_0;uart_config_t uart_config = {.baud_rate = 115200,.data_bits = UART_DATA_8_BITS,.parity    = UART_PARITY_DISABLE,.stop_bits = UART_STOP_BITS_1,.flow_ctrl = UART_HW_FLOWCTRL_DISABLE};uart_param_config(uart_num, &uart_config);uart_driver_install(uart_num, 2048, 0, 0, NULL, 0);uint8_t data[512];while (1){int len = uart_read_bytes(uart_num, data, sizeof(data) - 1, pdMS_TO_TICKS(1000));if (len > 0){data[len] = '\0';printf("UART Received: %s\n", data);cJSON *root = cJSON_Parse((char *)data);if (!root){printf("JSON Parse Error\n");}else{cJSON *ssid = cJSON_GetObjectItem(root, "ssid");cJSON *pass = cJSON_GetObjectItem(root, "pass");if (ssid && pass){// WiFi 賬號密碼配置strncpy(g_wifi_ssid, ssid->valuestring, sizeof(g_wifi_ssid) - 1);strncpy(g_wifi_pass, pass->valuestring, sizeof(g_wifi_pass) - 1);printf("Set WiFi SSID: %s\n", g_wifi_ssid);printf("Set WiFi PASS: %s\n", g_wifi_pass);wifi_connect();}else{// 透傳 POST 數據strncpy(g_post_json, (char *)data, sizeof(g_post_json) - 1);g_post_json[sizeof(g_post_json) - 1] = '\0';printf("POST JSON set: %s\n", g_post_json);xSemaphoreGive(xPostSemaphore); // 通知 POST 任務}cJSON_Delete(root);}}}
}// HTTP POST 任務
void http_post_task(void *pvParameters)
{while (1){if (xSemaphoreTake(xPostSemaphore, portMAX_DELAY) == pdTRUE){esp_http_client_config_t config = {.url = "http://sh-3-api.iot-api.com/device/v1/******/attributes",};esp_http_client_handle_t client = esp_http_client_init(&config);esp_http_client_set_method(client, HTTP_METHOD_POST);esp_http_client_set_header(client, "Content-Type", "application/json");esp_http_client_set_header(client, "Project-Key", PROJECT_KEY);esp_http_client_set_post_field(client, g_post_json, strlen(g_post_json));esp_err_t err = esp_http_client_perform(client);if (err == ESP_OK){printf("HTTP POST Status = %d, content_length = %d\n",esp_http_client_get_status_code(client),esp_http_client_get_content_length(client));}else{printf("HTTP POST request failed: %s\n", esp_err_to_name(err));}esp_http_client_cleanup(client);}}
}// ========== HTTP GET Task ==========
void http_get_task(void *pvParameters)
{while (1){esp_http_client_config_t config = {.url = "http://sh-3-api.iot-api.com/device/v1/*****/attributes",};esp_http_client_handle_t client = esp_http_client_init(&config);esp_http_client_set_method(client, HTTP_METHOD_GET);esp_http_client_set_header(client, "Content-Type", "application/json");esp_http_client_set_header(client, "Project-Key", PROJECT_KEY);esp_err_t err = esp_http_client_perform(client);if (err == ESP_OK){printf("HTTP GET Status = %d, content_length = %d\n",esp_http_client_get_status_code(client),esp_http_client_get_content_length(client));// ========== 循環讀取完整內容 ==========char buffer[512];int total_len = 0;while (1){int data_read = esp_http_client_read(client, buffer, sizeof(buffer) - 1);if (data_read <= 0)break;buffer[data_read] = 0; // 添加結束符printf("%s", buffer);  // 分塊打印total_len += data_read;}printf("\n[Total Read Length: %d]\n", total_len);}else{printf("HTTP GET request failed: %s\n", esp_err_to_name(err));}esp_http_client_cleanup(client);vTaskDelay(pdMS_TO_TICKS(15000)); // 每15s獲取一次}
}// LED 任務
void led_blink_task(void *pvParams)
{gpio_set_direction(LED_GPIO, GPIO_MODE_OUTPUT);while (1){gpio_set_level(LED_GPIO, 1);vTaskDelay(pdMS_TO_TICKS(500));gpio_set_level(LED_GPIO, 0);vTaskDelay(pdMS_TO_TICKS(500));}
}// Main
void app_main()
{nvs_flash_init();wifi_driver_init();xPostSemaphore = xSemaphoreCreateBinary();xTaskCreate(uart_receive_task, "uart_receive_task", 4096, NULL, 5, NULL);xTaskCreate(http_post_task, "http_post_task", 8192, NULL, 5, NULL);xTaskCreate(http_get_task, "http_get_task", 8192, NULL, 5, NULL);xTaskCreate(led_blink_task, "led_blink_task", 2048, NULL, 5, NULL);
}

7.效果(連接過的wifi會保存flash,每次發送WiFi賬密,會重新連接)

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/90540.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/90540.shtml
英文地址,請注明出處:http://en.pswp.cn/web/90540.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

ZLMediaKit 源代碼入門

ZLMediaKit 是一個基于 C11 開發的高性能流媒體服務器框架&#xff0c;支持 RTSP、RTMP、HLS、HTTP-FLV 等協議。以下是源代碼入門的詳細指南&#xff1a; 1. 源碼結構概覽 主要目錄結構&#xff1a; text ZLMediaKit/ ├── cmake/ # CMake 構建配置 ├── …

智能Agent場景實戰指南 Day 21:Agent自主學習與改進機制

【智能Agent場景實戰指南 Day 21】Agent自主學習與改進機制 文章內容 開篇 歡迎來到"智能Agent場景實戰指南"系列的第21天&#xff01;今天我們將深入探討智能Agent的自主學習與改進機制——這是使Agent能夠持續提升性能、適應動態環境的核心能力。在真實業務場景…

微信小程序中英文切換miniprogram-i18n-plus

原生微信小程序使用 miniprogram-i18n-plus第一步&#xff1a;npm install miniprogram-i18n-plus -S安裝完成后&#xff0c;會在項目文件文件夾 node_modules文件里生成 miniprogram-i18n-plus&#xff0c; 然后在工具欄-工具-構建npm&#xff0c;然后看到miniprogram_npm里面…

LeetCode 127:單詞接龍

LeetCode 127&#xff1a;單詞接龍問題本質&#xff1a;最短轉換序列的長度 給定兩個單詞 beginWord 和 endWord&#xff0c;以及字典 wordList&#xff0c;要求找到從 beginWord 到 endWord 的最短轉換序列&#xff08;每次轉換僅改變一個字母&#xff0c;且中間單詞必須在 wo…

docker搭建ray集群

1. 安裝docker 已安裝過docker 沒安裝流程 啟動 Docker 服務&#xff1a; sudo systemctl start docker sudo systemctl enable docker # 設置開機即啟動docker驗證 Docker 是否安裝成功&#xff1a; docker --version2. 部署ray # 先停止docker服務 systemctl stop docker…

【iOS】SideTable

文章目錄前言1??Side Table 的核心作用&#xff1a;擴展對象元數據存儲1.1 傳統對象的內存限制1.2 Side Table 的定位&#xff1a;集中式元數據倉庫2??Side Table 的底層結構與關聯2.1 Side Table 與 isa 指針的關系2.2 Side Table 的存儲結構2.3 SideTable 的工作流程3??…

【Spring Cloud Gateway 實戰系列】高級篇:服務網格集成、安全增強與全鏈路壓測

一、服務網格集成&#xff1a;Gateway與Istio的協同作戰在微服務架構向服務網格演進的過程中&#xff0c;Spring Cloud Gateway可與Istio形成互補——Gateway負責南北向流量&#xff08;客戶端到集群&#xff09;的入口管理&#xff0c;Istio負責東西向流量&#xff08;集群內服…

一文說清楚Hive

Hive作為Apache Hadoop生態的核心數據倉庫工具&#xff0c;其設計初衷是為熟悉SQL的用戶提供大規模數據離線處理能力。以下從底層計算框架、優點、場景、注意事項及實踐案例五個維度展開說明。 一、Hive底層分布式計算框架對比 Hive本身不直接執行計算&#xff0c;而是將HQL轉換…

SeaweedFS深度解析(三):裸金屬單機和集群部署

#作者&#xff1a;閆乾苓 文章目錄2.2.4 S3 Server&#xff08;兼容 Amazon S3 的接口&#xff09;2.2.5 Weed&#xff08;命令行工具&#xff09;3、裸金屬單機和集群部署3.1 裸金屬單機部署3.1.1安裝 SeaweedFS3.1.2 以Master模式啟動2.2.4 S3 Server&#xff08;兼容 Amazon…

相機ROI 參數

相機的 ROI&#xff08;Region of Interest&#xff0c;感興趣區域&#xff09; 參數&#xff0c;是指通過設置圖像傳感器上 特定區域 作為有效成像區域&#xff0c;從而只采集該區域的圖像數據&#xff0c;而忽略其他部分。這一功能常用于工業相機、科研相機、高速相機等場景&…

Vue基礎(24)_VueCompinent構造函數、Vue實例對象與組件實例對象

分析上一節代碼中的school組件&#xff1a;該組件是一個名為VueCompinent的構造函數。截取部分vue.js源碼&#xff0c;分析Vue.extend&#xff1a;// 定義一個名為VueComponent的構造函數對象Sub&#xff0c;往Sub對象調用_init(options)方法&#xff0c;參數為配置項&#xff…

螢石云替代產品攝像頭方案螢石云不支持TCP本地連接-東方仙盟

不斷試錯東方仙盟深耕科研測評&#xff0c;聚焦前沿領域&#xff0c;以嚴謹標準評估成果&#xff0c;追蹤技術突破&#xff0c;在探索與驗證中持續精進&#xff0c;為科研發展提供參考&#xff0c;助力探路前行 螢石云價格螢石云的不便于使用 家庭場景&#xff1a;成本可控與隱…

C51:用DS1302時鐘讀取和設置時間

因為在ds1302.c文件中包含了寫ds1302&#xff08;51向ds1302寫數據&#xff09;和讀ds1302&#xff08;51從ds1302讀數據&#xff09;的兩個函數&#xff0c;我們根據文件中提供的函數來寫讀取時間和設置時間的函數即可ds1302.c文件源碼如下&#xff0c;需要的同學可以參考一下…

webrtc整體架構

WebRTC&#xff08;Web Real-Time Communication&#xff09;是一套支持瀏覽器和移動應用進行實時音視頻通信的開源技術標準&#xff0c;其架構設計圍繞 “實時性”“低延遲”“跨平臺” 和 “安全性” 展開&#xff0c;整體可分為核心引擎層、API 層、支撐服務層三大部分&…

淺析PCIe 6.0 ATS地址轉換功能

在現代高性能計算和虛擬化系統中,地址轉換(Address Translation)是一個至關重要的機制。隨著 PCIe 設備(如 GPU、網卡、存儲控制器)直接訪問系統內存的能力增強,設備對虛擬內存的訪問需求日益增長。 為了提升性能并確保安全訪問,Address Translation Services(ATS) 應…

【前端】ikun-pptx編輯器前瞻問題二: pptx的壓縮包結構,以及xml正文樹及對應元素介紹

文章目錄PPTX文件本質&#xff1a;一個壓縮包核心文件解析1. 幻燈片內容文件 (ppt/slides/slideX.xml)2. 元素類型解析文本框元素 (p:sp)圖片元素 (p:pic)單位系統開發注意事項參考工具pptx渲染路線圖PPTX文件本質&#xff1a;一個壓縮包 PPTX文件實際上是一個遵循Open XML標準…

分布式任務調度實戰:XXL-JOB與Elastic-Job深度解析

告別傳統定時任務的局限&#xff0c;擁抱分布式調度的強大與靈活 在現代分布式系統中&#xff0c;高效可靠的任務調度已成為系統架構的核心需求。面對傳統方案&#xff08;如Timer、Quartz&#xff09;在分布式環境下的不足&#xff0c;開發者急需支持集群調度、故障轉移和可視…

Windows 11下純軟件模擬虛擬機的設備模擬與虛擬化(僅終端和網絡)

Windows 11下用GCC的C代碼實現的虛擬機需要終端輸入/輸出&#xff08;如串口或虛擬控制臺&#xff09;和網絡連接&#xff0c;但不需要完整的硬件設備&#xff08;如磁盤、顯卡、USB 等&#xff09;。在終端輸入/輸出方面&#xff0c;參考qemu的源代碼&#xff0c;但不調用qemu…

CCF-GESP 等級考試 2025年6月認證Python六級真題解析

1 單選題&#xff08;每題 2 分&#xff0c;共 30 分&#xff09;第1題 下列哪一項不是面向對象編程&#xff08;OOP&#xff09;的基本特征&#xff1f;&#xff08; &#xff09;A. 繼承 (Inheritance) B. 封裝 (Encapsul…

C++中的deque

1. 什么是 Deque&#xff1f; 核心概念&#xff1a; Deque 是 “Double-Ended Queue”&#xff08;雙端隊列&#xff09;的縮寫。你可以把它想象成一個可以在兩端&#xff08;頭部和尾部&#xff09;高效地進行添加或刪除操作的線性數據結構。關鍵特性&#xff1a; 雙端操作&am…