Home Assistant无法使用NodeMCU与伺服电机一起使用

问题描述

你好 我的代码中存在一些问题, NodeMCU 与wifi连接,然后与 Home Assistant 本地服务器连接,但是当我从Home Assistant向我的伺服电机发送命令时,伺服电机不会旋转。我认为问题出在我的 for循环中。任何帮助将不胜感激。

代码

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include<Servo.h> 

const char* ssid = "My ssid"; 
const char* password =  "my wifi password";

const char* mqttServer = "mqttServer ip 192.168.**.**";
const int mqttPort = 1883;
const char* mqttUser = "**My mqtt User name**";
const char* mqttPassword = "My mqtt Password ";

Servo myServo;
WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  myServo.attach(D1); //attaches the servo on pin D1
  Serial.begin(115200);
  WiFi.begin(ssid,password);
  client.setCallback(callback);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
  
  client.setServer(mqttServer,mqttPort);
  
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
    
    if (client.connect("ESP8266Client",mqttUser,mqttPassword )) {
      Serial.println("connected");
      client.subscribe("servemot");
      } else {
        Serial.print("Failed with state ");
        Serial.print(client.state());
        delay(2000);
      } 
  }
  
  //client.publish("esp/test","Hello from ESP8266");
  //client.subscribe("esp/test");
}

void callback(char* topic,byte* payload,unsigned int length){
  Serial.print("Command from MQTT broker is : [");
  Serial.print(topic);
  Serial.print(" Rotation angle is:");
  Serial.print("   ");
  for(int i=0;i<1;i++)
  {
    if((int)payload[i]>194||(int)payload[i]<0)
    break;
      myServo.write((int)payload[i]);// tell servo to go to position in variable '(int)payload[i]'
    Serial.println((int)payload[i]);//print the rotation angle
    Serial.println("]");
    Serial.println();
  }
}//end callback

void loop() {
  client.loop();
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)