开发工具 ardunio
nodemcu 开发板子
硬件
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Servo.h>
Servo servo;
WiFiClient espClient;
PubSubClient client(espClient);
const char *ssid = "16L-YiDong";
const char *password = "9622596225";
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "cat_push";
const char *mqtt_username = "cat11";
const char *mqtt_password = "cat123456";
const int mqtt_port = 1883;
const int ECH = D0;
const int DUO = D1;
int ishere = 0;
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(ECH, INPUT);
servo.attach(DUO);
shineled();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
const char *client_id = "esp8266-client-";
Serial.println("Connecting to public emqx mqtt broker.....");
if (client.connect(client_id, mqtt_username, mqtt_password)) {
Serial.println("Public emqx mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
client.publish(topic, "hello emqx");
client.subscribe(topic);
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char) payload[i]);
}
Serial.println();
Serial.println("-----------------------");
shineled();
client.publish("cat_rec", "hello emqx11111111111111111111111111");
}
void shineled() {
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
delay(200);
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
delay(200);
}
void getinputss() {
int value = digitalRead(ECH);
Serial.println(value);
if (value == HIGH)
{
if (ishere == 0) {
ishere = 1;
Duoji();
}
Serial.println("Someone!");
client.publish("cat_rec", "hello 有人靠近。。00。。");
} else {
if (ishere == 1) {
ishere = 0;
Duoji();
client.publish("cat_rec", "hello 已经离开。。。。。。。");
}
}
delay(500);
}
void Duoji() {
servo.write(60);
delay(100);
servo.write(120);
delay(100);
}
void loop() {
client.loop();
getinputss();
}