Hello everyone, I'm working on a project for school about reading the name of the song that is being played on Spotify. The information is being sent over from NodeRed to the public HiveMq broker and from there on to the serial monitor in Arduino.
The problem is that the name is getting printed every 4 seconds in my serial monitor and not just once. I would only want it to get printed once but I've tried everything I could think of and can't figure if out. I will attach my code.
#include <WiFi.h>
#include <PubSubClient.h>
#include <LiquidCrystal_I2C.h>
const char* ssid = "personal";
const char* password = "personal";
const char* mqtt_server = "broker.mqtt-dashboard.com";
LiquidCrystal_I2C lcd(0x3F, 16, 2);
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
char playingsong;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
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("Weergave payload=");
for (int i = 0; i < length; i++) {
playingsong = ((char)payload[i]);
Serial.print(playingsong);
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// ... and resubscribe
client.subscribe("ThiboSpotify");
}
else {
Serial.print("failed, rc=");
Serial.println(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);
lcd.init();
lcd.clear();
lcd.backlight();
lcd.setCursor(2, 0);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
}
I would highly appreciate some help with this. Thanks in advance!