NodeMCU не может заставить MQTT и сценарий светодиодной ленты работать вместе

#c #arduino-ide #nodemcu

#c #arduino-ide #nodemcu

Вопрос:

Я пытаюсь настроить NodeMCU v1 (с платой драйвера светодиода) для управления светодиодной лентой с помощью MQTT, сначала я начал с управления светодиодной лентой. для этого я использовал пакет LEDStripDriver, в котором есть некоторый пример кода, который я уменьшил, но все еще работает:

 #include "RGBdriver.h"
#define CLK 3//pins definitions for the driver        
#define DIO 2
RGBdriver Driver(CLK,DIO);
void setup()  
{ 

}  
void loop()  
{ 
  /*Function: SetColor()                              */
  /*Parameters: red:0~255                           */
  /*            green:0~255                         */
  /*            blue:0~255                          */
  /*Note: the greater the value,the brighter the LED*/
  Driver.begin();
  Driver.SetColor(100, 0, 0); //Red
  Driver.end();
  delay(5000);
  // other colors
  Driver.begin();
  Driver.SetColor(0, 0, 0);//all LED is off
  Driver.end();
  delay(5000);
}
 

Загрузка этого в NodeMCU работает отлично, и индикатор переключается с красного на выключенный, как и ожидалось, поэтому моя проводка правильная.

затем я взял пример для библиотеки MQTT, которую я использовал, это пример кода, который я использовал: https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_esp8266/mqtt_esp8266.ino и объединил код rgb ledstrip с этим, со следующим результатом:

 #include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <RGBdriver.h> // Including the RGBdriver package as in the example
#define CLK 3//pins definitions for the driver        
#define DIO 2

// Update these with values suitable for your network.

const char* ssid = "WIFI";
const char* password = "Password";
const char* mqtt_server = "192.168.1.x";

const int mqtt_port = 1883;
const char* mqtt_user = "username";
const char* mqtt_password = "password";

RGBdriver Driver(CLK,DIO); // here I placed the RGB driver initiator
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i  ) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    Serial.println("LED STRIP TO ON");
    Driver.begin();
    Driver.SetColor(0, 0, 100); //Blue when mqtt receives value of 1
    Driver.end();
  } else {
    Serial.println("LED STRIP TO OFF");
    Driver.begin();
    Driver.SetColor(0, 0, 0);//all LED off when mqtt receives value of 0
    Driver.end();
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId  = String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), mqtt_user, mqtt_password)) { // changed this from the example to enable login with username/password
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  //pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {
  // This is copied directly from the example, so I expected this at least to work
  Driver.begin();
  Driver.SetColor(100, 0, 0); //Red
  Driver.end();
  delay(5000);
  // other colors
  Driver.begin();
  Driver.SetColor(0, 0, 0);//all LED is off
  Driver.end();
  delay(5000);
  if (!client.connected()) {
    reconnect();
  }

  client.loop();

  unsigned long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
      value;
    snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}
 

Когда я загружаю приведенный выше код, он подключается к Wifi и серверу MQTT и публикует свои сообщения, а также подписывается на inTopic и отвечает на него, как показано в следующем последовательном журнале:

 Connecting to WIFI
scandone
scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 4
cnt 

connected with WIFI, channel 6
dhcp client start...
.....ip:192.168.1.47,mask:255.255.255.0,gw:192.168.1.1
.
WiFi connected
IP address: 
192.168.1.47
Attempting MQTT connection...connected
Publish message: hello world #1
Publish message: hello world #2
Publish message: hello world #3
Publish message: hello world #4
pm open,type:2 0
Publish message: hello world #5
Message arrived [inTopic] 1
LED STRIP TO ON
Publish message: hello world #6
Publish message: hello world #7
Message arrived [inTopic] 0
LED STRIP TO OFF
Publish message: hello world #8
 

таким образом, MQTT работает должным образом, и информация о сети настроена правильно,
однако светодиодная лента становится белой в тот момент, когда я начинаю загрузку из arduino IDE, и никогда не меняет свой цвет, также когда я публикую 1 или 0 в inTopic.
если я отключу все питание как от светодиодной ленты, так и от nodemcu, светодиодная лента останется выключенной до тех пор, пока я не загружу скрипт повторно.

Может ли кто-нибудь указать мне правильное направление, почему оба скрипта работают независимо, но светодиод перестает работать при объединении?