华佗养生网
您的当前位置:首页WIFI 开关

WIFI 开关

来源:华佗养生网

esp32  作为http  ap  server 控制led  。

esp32c3  作为遥控器,按下gpio4脚接高电平,唤醒深度睡眠的c3, 连接服务器,发送/open.

此无线开关高度低功耗,因为c3采用深度睡眠,平时功耗只有几微安。就是双方wifi连接时间有5至10秒左右时间。

遥控器端有led显示,如果没有连接上服务器,led灯一直点亮

如果能优化wifi连接的时间缩小为1,2秒左右,此方案就实用化了。

如果使用c3的wifi功能,必须进行电源功耗管理,因为它连接wifi发热太严重了。

实际使用中发现,不管怎样优化,不如把两者的物理距离缩短效果好,这样说明c3的wifi发射接收性能不好。如果两者的距离在半米之内,开启时间可以在3秒之内

1. led服务器端


#include <stdio.h>
#include <string.h>
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_http_server.h"
#include "driver/gpio.h"
#define WIFI_SSID "ESP32_AP"
#define WIFI_PASS "wz123456"
#define MAX_STA_CONN 4

#define GPIO_out  23       //控制led脚
static const char *TAG = "ESP32_AP_HTTP";

// HTTP GET 处理程序,响应 "OK"
esp_err_t open_handler(httpd_req_t *req) {
    	char resp_str[21]="led open"; 
		httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", "*");
		httpd_resp_set_type(req, "text/plain");
		httpd_resp_send(req, resp_str, HTTPD_RESP_USE_STRLEN); 
	    gpio_set_level(GPIO_out,1);
		 vTaskDelay(10000/portTICK_PERIOD_MS);     //led 亮10秒
		  gpio_set_level(GPIO_out,0);
	    return ESP_OK;
}


// 配置 HTTP 服务器并注册 URI 处理程序
httpd_handle_t start_webserver(void) {
    httpd_config_t config = HTTPD_DEFAULT_CONFIG();
    httpd_handle_t server = NULL;
    
    if (httpd_start(&server, &config) == ESP_OK) {
        httpd_uri_t ok_uri = {
            .uri       = "/open",
            .method    = HTTP_GET,
            .handler   = open_handler,
            .user_ctx  = NULL
        };
        httpd_register_uri_handler(server, &ok_uri);
		
    }
    return server;
}

// 初始化 AP 模式
void wifi_init_softap() {
    wifi_config_t wifi_config = {
        .ap = {
            .ssid = WIFI_SSID,
            .ssid_len = strlen(WIFI_SSID),
            .password = WIFI_PASS,
            .max_connection = MAX_STA_CONN,
            .authmode = WIFI_AUTH_WPA_WPA2_PSK,
			.channel = 6,
        },
    };
    if (strlen(WIFI_PASS) == 0) {
        wifi_config.ap.authmode = WIFI_AUTH_OPEN;
    }

    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &wifi_config));
    ESP_ERROR_CHECK(esp_wifi_start());

    ESP_LOGI(TAG, "AP initialized. SSID:%s password:%s", WIFI_SSID, WIFI_PASS);
}

void app_main(void) {
	  gpio_config_t io_conf = {};      
    io_conf.intr_type = GPIO_INTR_DISABLE;
    io_conf.mode = GPIO_MODE_OUTPUT;
    io_conf.pin_bit_mask = 1ULL<<GPIO_out;  
    io_conf.pull_down_en = 0;
    io_conf.pull_up_en = 0;
    gpio_config(&io_conf);
	
	
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_create_default_wifi_ap();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    wifi_init_softap();
    
    // 启动 HTTP 服务器
    start_webserver();
}


2.c3遥控器端


#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_http_server.h"
#include "esp_timer.h"
#include "driver/gpio.h"
#include "esp_sleep.h"

// WiFi 
#define WIFI_SSID "ESP32_AP"
#define WIFI_PASS "wz123456"

#include "esp_http_client.h"

#define SERVER_IP      "192.168.4.1"
#define URL_OPEN       "http://" SERVER_IP "/open"
#define URL_CLOSE      "http://" SERVER_IP "/close"

static const char *TAG = "HTTP_CLIENT";
 
static EventGroupHandle_t s_wifi_event_group;
static const int WIFI_CONNECTED_BIT = BIT0;


//----------------------
#define AJ  4          
#define LED 21          //led 不能接入0-10脚

static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
	if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
		esp_wifi_connect();  // 
	} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
		esp_wifi_connect();  // 
		ESP_LOGI(TAG, "...");
	} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
		ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
		ESP_LOGI(TAG, "IP: " IPSTR, IP2STR(&event->ip_info.ip));
		xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);  // 锟斤拷
	}
}

// WiFi 
void wifi_init_sta(void) {
	s_wifi_event_group = xEventGroupCreate();  // 
	
	//  NVS
	esp_err_t ret = nvs_flash_init();
	if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
		ESP_ERROR_CHECK(nvs_flash_erase());
		ret = nvs_flash_init();
	}
	ESP_ERROR_CHECK(ret);
	
	//  WiFi
	ESP_ERROR_CHECK(esp_netif_init());
	ESP_ERROR_CHECK(esp_event_loop_create_default());
	esp_netif_create_default_wifi_sta();
	
	wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
	ESP_ERROR_CHECK(esp_wifi_init(&cfg));
	
	ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL, NULL));
	ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL, NULL));
	
	//  WiFi 
	wifi_config_t wifi_config = {
		.sta = {
			.ssid = WIFI_SSID,
			.password = WIFI_PASS,
			 .channel = 6,
		},
	};
	ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));  // 
	ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
	esp_wifi_set_ps(WIFI_PS_NONE);
	ESP_ERROR_CHECK(esp_wifi_start());  //  WiFi
	
	ESP_LOGI(TAG, "WiFi ");
}


// HTTP GET 请求函数
void http_get_request(const char *url) {
    esp_http_client_config_t config = {
        .url = url,
    };
    esp_http_client_handle_t client = esp_http_client_init(&config);

    // 发送 GET 请求
    esp_err_t err = esp_http_client_perform(client);

    if (err !=ESP_OK) {
        ESP_LOGE(TAG, "HTTP GET request failed: %s", esp_err_to_name(err));
    }

    // 关闭客户端
    esp_http_client_cleanup(client);
}

void app_main(void) {
	  // 配置 LED GPIO 为输出模式   gpio 0 脚为1,led 亮
   gpio_config_t io_conf;
    io_conf.intr_type = GPIO_INTR_DISABLE;
    io_conf.mode = GPIO_MODE_OUTPUT;
    io_conf.pin_bit_mask = (1ULL << LED);
    io_conf.pull_down_en = 0;
    io_conf.pull_up_en = 0;
    gpio_config(&io_conf);
	 gpio_set_level(LED,1);
	 
   
     esp_sleep_wakeup_cause_t   hxbz = esp_sleep_get_wakeup_cause();  //取得唤醒的类型,第一次开机类型不属于gpio,led不亮

    // 判断是否是深度睡眠唤醒
    if (hxbz == ESP_SLEEP_WAKEUP_GPIO) {    //GPIO唤醒     if条件内的语句就是唤醒后要执行的语句,如连接WiFi都行
       	
		wifi_init_sta();
	
		EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT, pdFALSE, pdTRUE, portMAX_DELAY);
		if (bits & WIFI_CONNECTED_BIT) {
			ESP_LOGI(TAG, "WiFi ok");
		} else {
			ESP_LOGI(TAG, "WiFi no");
		}
			http_get_request(URL_OPEN);     //关断	
	} 
            //配置唤醒源
	 gpio_set_level(LED,0);
	gpio_deep_sleep_hold_dis();	    //在深度睡眠时禁用所有数字gpio pad保持功能。
	esp_deep_sleep_enable_gpio_wakeup((1ULL<<AJ), ESP_GPIO_WAKEUP_GPIO_HIGH); //high
	gpio_set_direction(AJ, GPIO_MODE_INPUT);	//GPIO定向,设置为输入或输出GPIO_NUM_4
    esp_deep_sleep_start();
	
	
}



3.各种优化后的c3客户端,连接时间少于5秒

#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_http_server.h"
#include "esp_timer.h"
#include "driver/gpio.h"
#include "esp_sleep.h"
#include "esp_netif.h"

// WiFi
#define WIFI_SSID "ESP32_AP"
#define WIFI_PASS "wz123456"

// Static IP configuration
#define STATIC_IP      "192.168.4.10"
#define STATIC_GW      "192.168.4.1"
#define STATIC_NETMASK "255.255.255.0"

#include "esp_http_client.h"

#define SERVER_IP      "192.168.4.1"
#define URL_OPEN       "http://" SERVER_IP "/open"
#define URL_CLOSE      "http://" SERVER_IP "/close"

static const char *TAG = "HTTP_CLIENT";
 
static EventGroupHandle_t s_wifi_event_group;
static const int WIFI_CONNECTED_BIT = BIT0;

#define AJ  4          
#define LED 21          // LED cannot be connected to pins 0-10

static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
	if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
		esp_wifi_connect();
	} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
		esp_wifi_connect();
		ESP_LOGI(TAG, "WiFi disconnected, reconnecting...");
	} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
		ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
		ESP_LOGI(TAG, "Static IP: " IPSTR, IP2STR(&event->ip_info.ip));
		xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
	}
}

// WiFi Initialization with Static IP
void wifi_init_sta(void) {
	s_wifi_event_group = xEventGroupCreate();

	// Initialize NVS
	esp_err_t ret = nvs_flash_init();
	if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
		ESP_ERROR_CHECK(nvs_flash_erase());
		ret = nvs_flash_init();
	}
	ESP_ERROR_CHECK(ret);
	
	// Initialize TCP/IP network interface
	ESP_ERROR_CHECK(esp_netif_init());
	ESP_ERROR_CHECK(esp_event_loop_create_default());
	esp_netif_t *netif = esp_netif_create_default_wifi_sta();

	// Stop DHCP client
	ESP_ERROR_CHECK(esp_netif_dhcpc_stop(netif));

	// Set static IP configuration
	esp_netif_ip_info_t ip_info;
	inet_pton(AF_INET, STATIC_IP, &ip_info.ip);
	inet_pton(AF_INET, STATIC_GW, &ip_info.gw);
	inet_pton(AF_INET, STATIC_NETMASK, &ip_info.netmask);
	ESP_ERROR_CHECK(esp_netif_set_ip_info(netif, &ip_info));

	wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
	ESP_ERROR_CHECK(esp_wifi_init(&cfg));
	
	ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL, NULL));
	ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL, NULL));
	
	// WiFi Configuration
	wifi_config_t wifi_config = {
		.sta = {
			.ssid = WIFI_SSID,
			.password = WIFI_PASS,
			.channel = 6,
			.sort_method = WIFI_CONNECT_AP_BY_SIGNAL,
			.threshold.authmode = WIFI_AUTH_WPA2_PSK,
			.bssid = { 0xbc,0xdd,0xc2,0xcd,0x26,0xf1 }
		},
	};
	ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
	ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
	esp_wifi_set_ps(WIFI_PS_NONE);
	ESP_ERROR_CHECK(esp_wifi_start());

	ESP_LOGI(TAG, "WiFi initialized with static IP");
}

// HTTP GET request function
void http_get_request(const char *url) {
	esp_http_client_config_t config = {
		.url = url,
	};
	esp_http_client_handle_t client = esp_http_client_init(&config);

	// Send GET request
	esp_err_t err = esp_http_client_perform(client);

	if (err != ESP_OK) {
		ESP_LOGE(TAG, "HTTP GET request failed: %s", esp_err_to_name(err));
	}

	// Cleanup
	esp_http_client_cleanup(client);
}

void app_main(void) {
	// Configure LED GPIO as output
	gpio_config_t io_conf;
	io_conf.intr_type = GPIO_INTR_DISABLE;
	io_conf.mode = GPIO_MODE_OUTPUT;
	io_conf.pin_bit_mask = (1ULL << LED);
	io_conf.pull_down_en = 0;
	io_conf.pull_up_en = 0;
	gpio_config(&io_conf);
	gpio_set_level(LED, 1);

	esp_sleep_wakeup_cause_t hxbz = esp_sleep_get_wakeup_cause();

	// Check if the wake-up is from deep sleep
	if (hxbz == ESP_SLEEP_WAKEUP_GPIO) {
		wifi_init_sta();
		
		EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, WIFI_CONNECTED_BIT, pdFALSE, pdTRUE, portMAX_DELAY);
		if (bits & WIFI_CONNECTED_BIT) {
			ESP_LOGI(TAG, "WiFi connected");
		} else {
			ESP_LOGI(TAG, "WiFi connection failed");
		}
		http_get_request(URL_OPEN);
	} 
	
	// Configure wake-up source
	gpio_set_level(LED, 0);
	gpio_deep_sleep_hold_dis();
	esp_deep_sleep_enable_gpio_wakeup((1ULL << AJ), ESP_GPIO_WAKEUP_GPIO_HIGH);
	gpio_set_direction(AJ, GPIO_MODE_INPUT);
	esp_deep_sleep_start();
}

 

 

 

 

 

 

 

因篇幅问题不能全部显示,请点此查看更多更全内容