This is my first time working with Arduino, an esp32 and MQTT. I made a motion sensor that prints to an LCD when it senses movement and publishes a message to mqtt, but it loops on forever. I am trying to make it so it will only start when start is published through mqtt and stops when stop is published. However, I am having some trouble figuring it out. Here is my current code (the main part excluding the MQTT set up), and I've been told putting it in callback may help but I get an error saying "a function-definition is not allowed here before '{' token" referring to void loop. Any suggestions are appreciated.
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("-----------------------");
}
void loop() {
client.loop();
int motion = digitalRead(sensorPin);
if (motion == HIGH)
{
lcd.setCursor(0, 0);
lcd.print("!!!!!MOTION!!!!!");
client.publish(topic, "MOTION");
delay(100);
}
else
{
lcd.setCursor(0, 0);
lcd.print(" no motion ");
client.publish(topic, "NO MOTION");
delay(500);
}
}