Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /***********************************
- Joseph Naim
- Coffee Machine Servo over MQTT
- ************************************/
- int servo_neutral = 6400;
- int servo_button1 = 5400;
- int servo_button2 = 7400;
- int servo_gpio = 22;
- #include <esp32-hal-ledc.h>
- #include <WiFi.h>
- #include <PubSubClient.h>
- // Replace the next variables with your SSID/Password combination
- const char* ssid = "YOUR SSID";
- const char* password = "YOUR PASSWORD";
- // Add your MQTT Broker IP:
- const char* mqtt_server = "YOUR BROKER IP";
- const char* mqtt_username = "YOUR BROKER USERNAME";
- const char* mqtt_password = "YOUR BROKER PASSWORD";
- WiFiClient espClient;
- PubSubClient client(espClient);
- long lastMsg = 0;
- char msg[50];
- int value = 0;
- void setup() {
- Serial.begin(115200);
- setup_wifi();
- client.setServer(mqtt_server, 1883);
- client.setCallback(callback);
- ledcSetup(1, 50, 16); // channel 1, 50 Hz, 16-bit width
- ledcAttachPin(servo_gpio, 1); // GPIO 22 assigned to channel 1
- ledcWrite(1, servo_neutral); // Moved the servo to neutral
- }
- void setup_wifi() {
- delay(10);
- // Connect 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(".");
- }
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- }
- void callback(char* topic, byte* message, unsigned int length) {
- Serial.print("Message arrived on topic: ");
- Serial.print(topic);
- Serial.print(". Message: ");
- String messageCoffee;
- for (int i = 0; i < length; i++) {
- Serial.print((char)message[i]);
- messageCoffee += (char)message[i];
- }
- Serial.println();
- if(messageCoffee == "long")
- ledcWrite(1, servo_button1);
- delay(200);
- ledcWrite(1, servo_neutral);
- if(messageCoffee == "short")
- ledcWrite(1, servo_button2);
- delay(200);
- ledcWrite(1, servo_neutral);
- if (String(topic) == "cmnd/coffeemachine/output") {
- Serial.print("Changing output to ");
- if(messageCoffee == "long"){
- Serial.println("long");
- }
- if(messageCoffee == "short"){
- Serial.println("short");
- }
- }
- }
- void loop() {
- while (!client.connected()) {
- Serial.println("Connecting to MQTT...");
- if (client.connect("ESP Coffee Servo", mqtt_username, mqtt_password )) {
- Serial.println("connected");
- // Subscribe
- client.subscribe("cmnd/coffeemachine");
- } else {
- Serial.print("failed with state ");
- Serial.println(" try again in 5 seconds");
- // Wait 5 seconds before retrying
- delay(5000);
- }
- }
- client.loop();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement