#include <WiFi.h>
#include <PubSubClient.h>
#include <SevSeg.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqttServer = "broker.emqx.io";
char clientId[50];
SevSeg sevseg;
WiFiClient espClient;
PubSubClient client(espClient);
// #define NUM_LEDS 1
// #define DATA_PIN 5
// #define CLOCK_PIN 13
// CRGB leds[NUM_LEDS];
void setup() {
Serial.begin(115200);
byte numDigits = 4;
byte digitPins[] = {14, 15, 2, 5};
byte segmentPins[] = {12, 4, 19, 26, 27, 13, 18, 25};
bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
byte hardwareConfig = COMMON_ANODE; // See README.md for options
bool updateWithDelays = false; // Default 'false' is Recommended
bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected. Then, you only need to specify 7 segmentPins[]
sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments,
updateWithDelays, leadingZeros, disableDecPoint);
wifiConnect();
client.setServer(mqttServer, 1883);
client.setCallback(callback);
// FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}
void wifiConnect() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
void mqttReconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
int r = rand();
sprintf(clientId, "clientId-%d", r);
if (client.connect(clientId)) {
Serial.print(clientId);
Serial.println(" connected");
client.subscribe("topicName/test");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void callback(char* topic, byte* message, unsigned int length) {
String stMessage;
for (int i = 0; i < length; i++) {
stMessage += (char)message[i];
}
Serial.print(stMessage);
// int data = stMessage.toInt();
int data = 1221;
sevseg.setNumber(data);
sevseg.refreshDisplay();
delay(1); // This speeds up the simulation
// if(stMessage == "red"){
// leds[0] = CRGB::Red;
// FastLED.show();
// delay(500);
// }
// else if (stMessage == "blue"){
// leds[0] = CRGB::Blue;
// FastLED.show();
// delay(500);
// }
// else if (stMessage == "green"){
// leds[0] = CRGB::Green;
// FastLED.show();
// delay(500);
// }
// else{
// Serial.println("No color!");
// }
// delay(500);
}
void loop() {
delay(100);
if (!client.connected()) {
mqttReconnect();
}
client.loop();
}