MQTT between Arduino and Processing

Aus hyperdramatik
Zur Navigation springen Zur Suche springen

Arduino Code

///////////////////////////////////////////////////////////////////////////////////
// Code for ESP32 DEV MODULE 38pin version
///////////////////////////////////////////////////////////////////////////////////
// Example for sending & receiving messages via an MQTT broker with an ESP32
// Send integers '0' or '1' to the address "/led" to turn on/off an LED on pin14.
// Every time the analog sensor value on pin36 goes bellow the "threshold" value
// a message is sent to the address "/sensor" with the current sensor value.
///////////////////////////////////////////////////////////////////////////////////
// based on Shiftr.io example code by Joël Gähwiler:
// https://shiftr.io/try
// https://www.shiftr.io/docs/manuals/arduino
// https://github.com/256dpi/arduino-mqtt
// this code is intended for use with the Shifr Desktop App!
///////////////////////////////////////////////////////////////////////////////////
// when uploading code: sometimes necessairy
// to presss&hold the "BOOT" button
// when you see the following lines:
// "Connecting........_____....._____....."
/////////////////////////////////////////////////

#include <WiFi.h>
#include <MQTT.h>

const char ssid[] = "ladenlokal";
const char pass[] = "puppe2010";

WiFiClient net;
MQTTClient client;

#define LED_PIN 35 //27
#define SENSOR_PIN 36
unsigned int ledState = LOW;
int sensorValue = 0;
int thresholdValue = 4000;

unsigned long lastMillis = 0;


void connect() {
  Serial.print("checking wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }

  Serial.print("\nconnecting...");
  while (!client.connect("arduino", "", "")) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("\nconnected!");

  client.subscribe("/led");
  // client.unsubscribe("/hello");
}


void messageReceived(String &topic, String &payload) {
  Serial.println("incoming: " + topic + " - " + payload);
}


void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(SENSOR_PIN, INPUT);
  digitalWrite(LED_PIN, ledState);

  Serial.begin(115200);
  WiFi.begin(ssid, pass);

  // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino.
  // You need to set the IP address directly.
  client.begin("192.168.236.90", 2883, net);
  client.onMessage(messageReceived);

  connect();
}


void loop() {
  client.loop();
  //delay(10);  // <- fixes some issues with WiFi stability

  if (!client.connected()) {
    connect();
  }

  // publish a message only when the sensor value goes bellow threshold:
  sensorValue = analogRead(SENSOR_PIN);
  if (sensorValue < thresholdValue) {
    //because we send Strings over MQTT we first need to convert:
    String sensorValueString = String(sensorValue); 
    client.publish("/sensor", sensorValueString);
    Serial.println(sensorValue);
  }

  // publish a message roughly every second:
  if (millis() - lastMillis > 1000) {
    lastMillis = millis();
    //client.publish("/hello", "world");
  }
}


// function for turning on/off the LED
// depending on if one recives 1/0:
void led(int LED_on_off) {
  ledState = LED_on_off;
  digitalWrite(LED_PIN, ledState);
  Serial.print("/led: ");
  Serial.println(ledState);
}

Processing Code

///////////////////////////////////////////////////////////////////////////////////
// Code for ESP32 DEV MODULE 38pin version
///////////////////////////////////////////////////////////////////////////////////
// Example for sending & receiving messages via an MQTT broker with an ESP32
// Send integers '0' or '1' to the address "/led" to turn on/off an LED on pin14.
// Every time the analog sensor value on pin36 goes bellow the "threshold" value
// a message is sent to the address "/sensor" with the current sensor value.
///////////////////////////////////////////////////////////////////////////////////
// based on Shiftr.io example code by Joël Gähwiler:
// https://shiftr.io/try
// https://www.shiftr.io/docs/manuals/processing
// this code is intended for use with the Shifr Desktop App!
///////////////////////////////////////////////////////////////////////////////////
// when uploading code: sometimes necessairy
// to presss&hold the "BOOT" button
// when you see the following lines:
// "Connecting........_____....._____....."
/////////////////////////////////////////////////

import mqtt.*;

MQTTClient client;

String onOff = "0";
float backgroundShade = 0;

void setup() {
  size(400, 400);
  frameRate(25);

  client = new MQTTClient(this);
  client.connect("mqtt://192.168.236.90:2883", "processing");
}


void draw() {
  background(backgroundShade);
}


void mousePressed() {
  if (onOff == "0") {
    onOff = "1";
  } else onOff = "0";

  client.publish("/led", onOff);
}


void clientConnected() {
  println("client connected");
  client.subscribe("/sensor");
  client.subscribe("/hello");
}

float messageValue;

// incoming MQTT messages are forwarded to this messageReceived function:
void messageReceived(String topic, byte[] payload) {
  println("incoming MQTT message: " + topic + " - " + new String(payload));
  String str = new String(payload);
  int payloadInt = int(str);
  
  //if (topic == "/sensor") {
    println("sensor value: " + payloadInt);
    backgroundShade = map(payloadInt, 0, 4000, 0, 255);
  //}
  
}


void connectionLost() {
  println("connection lost");
}