背景:因为住在实验室,灯的开关离我的床很远,所以不想每次睡觉时还要下床关灯(其实就是懒)
先上视频预览一下:
智能开关灯
材料准备:MG90s舵机一个,esp8266 node mcu一个,充电宝一个,可传输数据的数据线一根,可能还需要热熔枪(具体看自己的插座布局)
先上arduino代码:
#define BLINKER_WIFI
#define BLINKER_PRINT Serial
#define BLINKER_MIOT_LIGHT
#include <Blinker.h>
#include <Servo.h>
char auth[] = ""; //点灯Key
char ssid[] = ""; //wifi名称
char pswd[] = ""; //wifi密码
BlinkerButton Button1("test1"); //blinker按键键名
BlinkerButton Button2("test2"); //blinker按键键名
Servo servo_16; //舵机输出口 GIPO16 D0口
bool oState = false;
//按键1按下后执行该函数
void button1_callback(const String & state) {
BLINKER_LOG("get button state: ", state);
// digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
servo_16.write(45); //舵机旋转角度 具体参数需要结合自身情况修改
delay(1); //给一个小延时
delay(1000); //舵机动作后延时一会回到初始位置
servo_16.write(95); //设置该角度方便手动开关灯 就是开完灯舵机归位
}
//按键2按下执行该函数
void button2_callback(const String & state) {
BLINKER_LOG("get button state: ", state);
servo_16.write(139); //同上一样的思路
delay(1);
delay(1000);
servo_16.write(95);
}
//小爱电源回调函数
//里面同样设置舵机的动作
void miotPowerState(const String & state)
{
BLINKER_LOG("need set power state: ", state);
if (state == BLINKER_CMD_ON) {
// digitalWrite(LED_BUILTIN, HIGH);
servo_16.write(45);
delay(1);
delay(1000);
servo_16.write(95);
BlinkerMIOT.powerState("on");
BlinkerMIOT.print();
}
else if (state == BLINKER_CMD_OFF) {
// digitalWrite(LED_BUILTIN, LOW);
servo_16.write(139);
delay(1);
delay(1000);
servo_16.write(95);
BlinkerMIOT.powerState("off");
BlinkerMIOT.print();
}
}
void miotQuery(int32_t queryCode)
{
BLINKER_LOG("MIOT Query codes: ", queryCode);
switch (queryCode)
{
case BLINKER_CMD_QUERY_ALL_NUMBER :
BLINKER_LOG("MIOT Query All");
BlinkerMIOT.powerState(oState ? "on" : "off");
BlinkerMIOT.print();
break;
case BLINKER_CMD_QUERY_POWERSTATE_NUMBER :
BLINKER_LOG("MIOT Query Power State");
BlinkerMIOT.powerState(oState ? "on" : "off");
BlinkerMIOT.print();
break;
default :
BlinkerMIOT.powerState(oState ? "on" : "off");
BlinkerMIOT.print();
break;
}
}
void dataRead(const String & data)
{
BLINKER_LOG("Blinker readString: ", data);
Blinker.vibrate();
uint32_t BlinkerTime = millis();
Blinker.print(BlinkerTime);
Blinker.print("millis", BlinkerTime);
}
void setup()
{
Serial.begin(115200);
BLINKER_DEBUG.stream(Serial);
// 初始化
pinMode(LED_BUILTIN, OUTPUT);
servo_16.attach(16);
// servo_16.write(90);//上电时舵机归零垂直
digitalWrite(LED_BUILTIN, HIGH);
// 初始化blinker
Blinker.begin(auth, ssid, pswd);
BlinkerMIOT.attachQuery(miotQuery);
Blinker.attachData(dataRead);
BlinkerMIOT.attachPowerState(miotPowerState);
Button1.attach(button1_callback);
Button2.attach(button2_callback);
}
void loop()
{
Blinker.run();
}
char auth[] = ""; //点灯Key
char ssid[] = ""; //wifi名称
char pswd[] = ""; //wifi密码
分别是你在点灯科技软件中申请的点灯key,以及wifi名称和密码(必须是2.4GHZ的wifi)
代码可以实现舵机开完灯或者关完灯后,自动返回初始位置,无需手动调整。当然还可以接入点灯科技进行控制,详细的可以看我下面的教程。
所需文件以及详细教程如下链接:
链接:https://pan.baidu.com/s/1OlD51znmY8Z_ZnwSJj65TA
提取码:1111