want to change the value of msg.payload from Arduino and send it to the node. How can I send red or blue to the node when I set the variable data in mongodb?

Aduino successfully sent the value to msg.payload, but if syntax is used, it is not known whether the value has changed or not.

// When a character is received from a communication, it is stored in a //payload array of this function. //Only the smallest possible code has been pasted.

//The operation is to send values to the node using mqtt communication.

//Arduino Source code -------

enter code here

String sChipID;
char cChipID[20];

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[255];

//rotary encoder inputs
int S = D1;     // SW, Switch
#define inputDT D2  // DT, OutA
#define inputCLK D3  // CLK, OutB

//rgb smd
int d5=D5;      //B
int d6=D6;      //R
int d7=D7;      //G

int counter = 0; 
int currentStateCLK;
int previousStateCLK; 

String encdir ="";


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();

  String s;
  deserializeJson(doc,payload);
  root = doc.as<JsonObject>();

}


//A value is output to the counter using a rotary encoder
//ex)"Direction:--Value: 10 
//    10

void loop(){             
    if (!client.connected()) {
    reconnect();
  }
  client.loop();

   currentStateCLK = digitalRead(inputCLK);

   if (currentStateCLK != previousStateCLK){ 

     if (digitalRead(inputDT) != currentStateCLK) { 
       counter --;
       encdir ="CCW";
       digitalWrite(d5,0);   //B
       digitalWrite(d6,255); //R
       digitalWrite(d7,0);   //G  

       sprintf(msg,"%d",counter);

     } else {
       counter ++;
       encdir ="CW";
       digitalWrite(d5,255); //B
       digitalWrite(d6,0);   //R
       digitalWrite(d7,0);   //G

       sprintf(msg,"%d",counter);
     }
     Serial.print("Direction: ");
     Serial.print(encdir);
     Serial.print(" -- Value: ");
     Serial.println(counter);
     //
     Serial.println(msg);
     client.publish(outTopic, msg);  // The value is sent to msg.payload.

   } 
   previousStateCLK = currentStateCLK; 



//node-red function

if(msg.payload>1)
msg.payload="{\"chipid\":\"eab916\"\, \"act\":\"write\"\,\"data\":"+1+"}";
else
msg.payload="{\"chipid\":\"eab916\"\, \"act\":\"write\"\,\"data\":"+0+"}";
return msg;


//mongodb

{
    "_id" : ObjectId("5ce90950c088f32b1250a7e9"),
    "name" : "rotary",
    "chipid" : "eab916",
    "data" : "red"
}

As expected, as the value rises and falls, the red is recognized in mongdb and the output is changed to the node-red, but it does not change.

0 Answers