esp8266,成功代码集
esp8266,成功代码集

esp8266,成功代码集

同上一篇文章

一、点灯科技配网+按钮点亮指示灯

需要库Blinker OneButton

参考文档:https://diandeng.tech/doc/getting-start-8266,https://diandeng.tech/doc/config-tool

#define BLINKER_WIFI
#define BLINKER_ESP_SMARTCONFIG

#include <Blinker.h>

// Download OneButton library here:
// https://github.com/mathertel/OneButton
#include "OneButton.h"

#if defined(ESP32)
    #define BLINKER_BUTTON_PIN 4
#else
    #define BLINKER_BUTTON_PIN D7
#endif
// button trigged when pin input level is LOW
OneButton button(BLINKER_BUTTON_PIN, true);

char auth[] = "ec712f5d8f38";



// other

BlinkerButton Button1("btn-abc");
BlinkerNumber Number1("num-abc");

int counter = 0;

// 按下按键即会执行该函数
void button1_callback(const String & state) {
    BLINKER_LOG("get button state: ", state);
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}
// other end


// 如果未绑定的组件被触发,则会执行其中内容
void dataRead(const String & data)
{
    BLINKER_LOG("Blinker readString: ", data);
    counter++;
    Number1.print(counter);
}



void deviceReset()
{
    // Reset device ,erase WiFi config.
    Blinker.reset();
}



void setup()
{
    Serial.begin(115200);
    BLINKER_DEBUG.stream(Serial);

    pinMode(LED_BUILTIN, OUTPUT);

    
    Blinker.begin(auth);
    Blinker.attachData(dataRead);

    Button1.attach(button1_callback);    
    button.attachLongPressStop(deviceReset);



}

void loop()
{
    Blinker.run();
    button.tick();
}

APP端设置:

二、阿里云物联网/网页控制

详细信息:同上篇文章

#include <ESP8266WiFi.h>

/*** 该工程可以在2.4.0版本esp8266库中运行,没在更高版本库中进行测试 ***/

#include <ESP8266WiFi.h>
static WiFiClient espClient;

// 引入阿里云 IoT SDK
#include <AliyunIoTSDK.h>

// 设置产品和设备的信息,从阿里云设备信息里查看
#define PRODUCT_KEY "a1??ox????"
#define DEVICE_NAME "led3"
#define DEVICE_SECRET "428f????????4f09ac8"
#define REGION_ID "cn-shanghai"

#define WIFI_SSID "Chi???wL????"
#define WIFI_PASSWD "i???d8i"

const char *ssid = "Chin???y3";
const char *password = "idL??d8i";

WiFiServer server(80);

String readString = ""; //建立一个字符串对象用来接收存放来自客户的数据


//响应头
String responseHeaders =
    String("") +
    "HTTP/1.1 200 OK\r\n" +
    "Content-Type: text/html\r\n" +
    "Connection: close\r\n" +
    "\r\n";

//网页
String myhtmlPage =
    String("") +
    "<html>" +
    "<head>" +
    "    <title>luqizhi's web</title>" +
    "    <script defer=\"defer\">" +
    "        function ledSwitch() {" +
    "            var xmlhttp;" +
    "            if (window.XMLHttpRequest) {" +
    "                xmlhttp = new XMLHttpRequest();" +
    "            } else {" +
    "                xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");" +
    "            }" +
    "            xmlhttp.onreadystatechange = function () {" +
    "                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {" +
    "                    document.getElementById(\"txtState\").innerHTML = xmlhttp.responseText;" +
    "                }" +
    "            }," +
    "            xmlhttp.open(\"GET\", \"Switch\", true);" +
    "            xmlhttp.send(); " +
    "        }" +
    "    </script>" +
    "</head>" +
    "<body>" +
    "    <div id=\"txtState\">Unkwon</div>" +
    "    <input type=\"button\" value=\"Switch\" onclick=\"ledSwitch()\">" +
    "</body>" +
    "</html>";

bool LEDSwitch = 1; // 记录LED状态

void setup()
{
    pinMode(LED_BUILTIN, OUTPUT);

    digitalWrite(LED_BUILTIN, LOW); // 点亮LED
    
    digitalWrite(LED_BUILTIN, HIGH); // 熄灭LED

    
    Serial.begin(115200);
    Serial.println();

    Serial.printf("Connecting to %s ", ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println(" connected");

    server.begin();
    Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());

    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, HIGH);
    


    // 初始化 wifi
    wifiInit(WIFI_SSID, WIFI_PASSWD);
    
    // 初始化 iot,需传入 wifi 的 client,和设备产品信息
    AliyunIoTSDK::begin(espClient, PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET, REGION_ID);
    
    // 绑定一个设备属性回调,当远程修改此属性,会触发 ledSwitchCallback
    // PowerSwitch 是在设备产品中定义的物联网模型的 id
    AliyunIoTSDK::bindData("powerstate", ledSwitchCallback);



}

void loop()
{

    AliyunIoTSDK::loop();


    WiFiClient client = server.available(); //尝试建立客户对象
    if (client)                             //如果当前有客户可用
    {
        boolean currentLineIsBlank = true;
        Serial.println("[Client connected]");

        while (client.connected()) //如果客户端建立连接
        {
            if (client.available()) //等待有可读数据
            {
                char c = client.read(); //读取一字节数据
                readString += c;        //拼接数据
                /************************************************/
                if (c == '\n' && currentLineIsBlank) //等待请求头接收完成(接收到空行)
                {
                    //比较接收到的请求数据
                    if (readString.startsWith("GET / HTTP/1.1")) //如果是网页请求
                    {
                        client.print(responseHeaders); //向客户端输出网页响应
                        client.print(myhtmlPage);      //向客户端输出网页内容
                        client.print("\r\n");
                    }
                    else if (readString.startsWith("GET /Switch")) //如果是改变LED状态请求
                    {
                        if (LEDSwitch == 1)
                        {
                            digitalWrite(LED_BUILTIN, 0); // 点亮LED
                            client.print("LED has been turn on");
                            delay(1000);
                            LEDSwitch = 0;
                            
                        }                            

                        else
                        {
                            digitalWrite(LED_BUILTIN, 1); // 熄灭LED
                            client.print("LED has been turn off");
                            delay(1000);
                            LEDSwitch = 1;
                            
                            
                        }
                    }
                    else
                    {
                        client.print("\r\n");
                    }
                    break;
                }

                if (c == '\n')
                {
                    currentLineIsBlank = true; //开始新行
                }
                else if (c != '\r')
                {
                    currentLineIsBlank = false; //正在接收某行中
                }
                /************************************************/
            }
        }
        delay(1);      //等待客户完成接收
        client.stop(); //结束当前连接:
        Serial.println("[Client disconnected]");

        Serial.println(readString); //打印输出来自客户的数据
        readString = "";
    }

    if (LEDSwitch == 1)
    {

       client.print("LED has been turn on");

    }                            

    else
    {
       client.print("LED has been turn off");

                            
                            
    }
}



// 初始化 wifi 连接
void wifiInit(const char *ssid, const char *passphrase)
{
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, passphrase);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.println("WiFi not Connect");
    }
    Serial.println("Connected to AP");
}

// LED状态修改的回调函数
void ledSwitchCallback(JsonVariant p)
{
    int LEDSwitch = p["powerstate"];
    // 变更LED状态
    Serial.println(LEDSwitch);
    if (LEDSwitch==1)
    {
    
        digitalWrite(LED_BUILTIN, 0);
    }
    else
    {
        digitalWrite(LED_BUILTIN, 1);
    }
    
}

三、计划

接入阿里云生活物联网或点灯科技中的天猫精灵,小爱同学等语音助手。点亮显示屏,驱动舵机等(未购买)

Best Wishes.

lokizi 2021.12.3 23:47

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

wp-puzzle.com logo