#include <PubSubClient.h>
#include <WiFi.h> // Include the WiFi library if you're using WiFi for MQTT
const char* ssid = "Wokwi-Guest";
const char* password = "";
const char* mqttServer = "53617c9409644f51b8599da76015a496.s2.eu.hivemq.cloud";
const int mqttPort = 8883; // MQTT broker port
const int buttonPin1 = 34;
const int buttonPin2 = 35;
const int buttonPinplaypause = 32;
const int BUZZER_PIN = 18;
int button1State = 0;
int button2State = 0;
int button3State = 0;
const char* buttonTopic1 = "button1";
const char* buttonTopic2 = "button2";
const char* buttonTopic3 = "button3";
const char* buzzerTopic = "buzzer";
bool musicState = false;
int currenttoneindex = 0;
int tones[3] = {1000, 2000, 3000};
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
setupWifi();
client.setServer(mqttServer, mqttPort);
pinMode(BUZZER_PIN, OUTPUT);
}
void setupWifi() {
delay(10);
Serial.println("Connecting to WiFi");
WiFi.begin(ssid, password);
int attempts=0;
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println(".");
attempts++;
if(attempts >20){
Serial.println("failed");
while(true){
delay(1000);
}
}
}
Serial.println("Connected to WiFi");
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
int newButton1State = digitalRead(buttonPin1);
int newButton2State = digitalRead(buttonPin2);
int newButton3State = digitalRead(buttonPinplaypause);
if (newButton1State == HIGH && button1State == LOW) {
// Button 1 logic - Increase tone
toneAndPublish(tones[currenttoneindex]);
currenttoneindex = (currenttoneindex + 1) % (sizeof(tones) / sizeof(tones[0]));
}
if (newButton2State == HIGH && button2State == LOW) {
// Button 2 logic - Play a sequence
playSequence();
}
if (newButton3State == HIGH && button3State == LOW) {
// Button 3 logic - Decrease tone
toneAndPublish(tones[currenttoneindex]);
currenttoneindex = (currenttoneindex - 1 + sizeof(tones) / sizeof(tones[0])) % (sizeof(tones) / sizeof(tones[0]));
}
// Update button states for the next iteration
button1State = newButton1State;
button2State = newButton2State;
button3State = newButton3State;
}
void reconnect() {
while (!client.connected()) {
if (client.connect("arduinoClient")) {
Serial.println("Connected to MQTT broker");
} else {
Serial.print("Failed, rc=");
Serial.print(client.state());
Serial.println(" Retrying in 5 seconds...");
delay(5000);
}
}
}
void toneAndPublish(int frequency) {
tone(BUZZER_PIN, frequency);
delay(1000); // Adjust delay as needed
noTone(BUZZER_PIN);
client.publish(buzzerTopic, String(frequency).c_str());
}
void playSequence() {
for (int i = 0; i < 2; ++i) {
toneAndPublish(1500);
delay(200);
toneAndPublish(2000);
delay(200);
}
}