// This example shows how to connect to Cayenne using an ESP32 and send/receive sample data.
// Make sure you install the ESP32 Board Package and select the correct ESP32 board before compiling.
// To install the ESP32 Board Package follow the instructions here: https://github.com/espressif/arduino-esp32/blob/master/README.md#installation-instructions.
//#define CAYENNE_DEBUG
#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP32.h>
#include <ESP32Servo.h>
// WiFi network info.
char ssid[] = "Wokwi-GUEST";
char wifiPassword[] = "";
// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "dee2b560-ddec-11e8-898f-c12a468aadce";
char password[] = "65abec1da98129fe21ddf53b1cd8970626be11ad";
char clientID[] = "93df8e90-14d7-11ee-9ab8-d511caccfe8c";
#define rele_CHANNEL 20
#define rele_PIN 12
#define servo_channel 52
#define ACTUATOR_PIN 2
Servo s1;
unsigned long lastMillis = 0;
void setup() {
Serial.begin(9600);
Cayenne.begin(username, password, clientID, ssid, wifiPassword);
s1.attach(ACTUATOR_PIN);
pinMode(rele_PIN, OUTPUT);
}
void loop() {
Cayenne.loop();
}
// Default function for sending sensor data at intervals to Cayenne.
// You can also use functions for specific channels, e.g CAYENNE_OUT(1) for sending channel 1 data.
CAYENNE_OUT_DEFAULT()
{
// Write data to Cayenne here. This example just sends the current uptime in milliseconds on virtual channel 0.
Cayenne.virtualWrite(0, millis()/1000);
// Some examples of other functions you can use to send data.
//Cayenne.celsiusWrite(1, 22.0);
//Cayenne.luxWrite(2, 700);
//Cayenne.virtualWrite(3, 50, TYPE_PROXIMITY, UNIT_CENTIMETER);
}
// Default function for processing actuator commands from the Cayenne Dashboard.
// You can also use functions for specific channels, e.g CAYENNE_IN(1) for channel 1 commands.
CAYENNE_IN_DEFAULT()
{
CAYENNE_LOG("Channel %u, value %s", request.channel, getValue.asString());
//Process message here. If there is an error set an error message using getValue.setError(), e.g getValue.setError("Error message");
//int position = getValue.asDouble();
// Move the servo to the specified position.
//s1.write(position);
//Serial.println("position");
}
CAYENNE_IN(servo_channel)
{
// Determine angle to set the servo.
int position = getValue.asDouble();
// Move the servo to the specified position.
s1.write(position);
Serial.println("position");
}
CAYENNE_IN(rele_CHANNEL)
{
// Write value to turn the relay switch on or off. This code assumes you wire your relay as normally open.
if (getValue.asInt() == 0) {
digitalWrite(rele_PIN, LOW);
s1.write(90);
}
else {
digitalWrite(rele_PIN, HIGH);
s1.write(0);
}
}