Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <AccelStepper.h>
// Wifi network details and MQTT broker IP
const char* ssid = "xxx";
const char* password = "xxx";
const char* mqtt_server = "xx.xx.xx.xx";
const char* mqtt_user = "xxx";
const char* mqtt_password = "xxx";
int mqtt_port = xxxxx;
WiFiClient espClient;
PubSubClient client(espClient);
String switch1;
String strTopic;
String strPayload;
long current_position = 0;
// Define a stepper and the pins it will use
AccelStepper stepper(AccelStepper::DRIVER, 13, 12); // 13-PUL,12-DIR
int togglePin = 14; //Switches the driver module on/off
void setup_wifi() {
delay(10);
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* payload, unsigned int length) {
payload[length] = '\0';
strTopic = String((char*)topic);
if(strTopic == "gong/Control")
{
switch1 = String((char*)payload);
if(switch1 == "1")
{
Serial.println("1");
digitalWrite(togglePin, HIGH);
stepper.runToNewPosition(-200);
stepper.runToNewPosition(0);
}
else if(switch1 == "2")
{
Serial.println("2");
digitalWrite(togglePin, HIGH);
stepper.runToNewPosition(-250);
stepper.runToNewPosition(0);
}
else if(switch1 == "3")
{
Serial.println("3");
digitalWrite(togglePin, HIGH);
stepper.runToNewPosition(-300);
stepper.runToNewPosition(0);
}
else if(switch1 == "4")
{
Serial.println("4");
digitalWrite(togglePin, HIGH);
stepper.runToNewPosition(-300);
stepper.runToNewPosition(0);
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("gong", mqtt_user, mqtt_password)) {
Serial.println("connected");
// Once connected, publish an announcement...
client.subscribe("gong/Control");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
//set pin modes
pinMode(togglePin, OUTPUT);
digitalWrite(togglePin, LOW);
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
Serial.println("READY");
//configure stepper
stepper.setAcceleration(4000);
stepper.setCurrentPosition(0);
stepper.setMaxSpeed(1500);
//set pin modes
pinMode(togglePin, OUTPUT);
digitalWrite(togglePin, LOW);
}
void loop() {
if (stepper.run() != true) {
digitalWrite(togglePin, LOW);
}
if (WiFi.status() != WL_CONNECTED) {
setup_wifi();
}
if (!client.connected()) {
reconnect();
}
client.loop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment