esp8266使用arduino 开发mqtt 控制9g舵机

#include "ESP8266WiFi.h"
#include 
#include 
#include "ServoEasing.hpp"

#define LED 16  //D0
#define SERVO1_PIN 14         // 舵机脚位  D5

ServoEasing Servo1;                      // 舵机操作对象


WiFiClient espClient;  // wifi client
ESP8266WiFiMulti wifis;
PubSubClient mqttClient(espClient);  // mqtt client

void handleMessage(char *topic, byte *payload, unsigned int length) {
  Serial.printf("Message arrived in topic: %s \n", topic);
  String str;
  for (int i = 0; i < length; i++) {
    str += (char)payload[i];
  }
  if(str=="ledon") {
    Servo1.easeTo(180,360);
  }else if(str=="ledoff") {
     Servo1.easeTo(0,360);
  }
  // /*串口打印输出显示*/
  Serial.printf(str);
  Serial.println("--------------------------------------");
  digitalWrite(LED, LOW);
  delay(200);
}

// mqtt 连接
void connectMqttServer() {
  String clientId = "esp8266-" + WiFi.macAddress();
  if (mqttClient.connect(clientId.c_str(), "test", "123456")) {
    Serial.println("mqtt connected");
    mqttClient.subscribe("18512345678/mysmarthome/pub");
  }
}
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(LED, OUTPUT);
  Servo1.attach(SERVO1_PIN,0);
  wifis.addAP("CMCC-TNWz", "yrHMWZ3X");
  Serial.print("wifi start connect");
  while (wifis.run() != WL_CONNECTED) {
  }
  Serial.println();
  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  mqttClient.setServer("broker.tusk.link", 1883);
  mqttClient.setKeepAlive(60);
  mqttClient.setCallback(handleMessage);
  connectMqttServer();
}

void loop() {
  // wifi已连接
  if (wifis.run() == WL_CONNECTED) {
    if (mqttClient.connected()) {
      digitalWrite(LED, HIGH);
      mqttClient.loop();  // 发送心跳
    } else {
      digitalWrite(LED, LOW);
      connectMqttServer();
    }
  }
}

你可能感兴趣的:(esp8266,arduino)