#include "AccelStepper.h"
#define XSTEP 15
#define XDIR 4
#define DRIVER 1
#define FWD 2
#define REV 1
#define STOP 0
AccelStepper stepper(DRIVER, XSTEP, XDIR);
struct STRUCT1 {
byte xData = STOP;
} xTX;
struct STRUCT2 {
byte xData = STOP;
} xRX;
byte xState = 0, lastTXxState = 0, lastRXxState = 0;
bool move = false;
void setup(){
Serial.begin(115200);
stepper.setMaxSpeed(1000);
stepper.setAcceleration(30);
stepper.setSpeed(50);
stepper.stop();
}
void loop() {
int val = analogRead(34); //Transmitter Logic
int xAxis = map(val, 0, 4095, -100, 100);
if(xAxis < 0 || xAxis > 0){ //Creates State from Joystick Input
if(xAxis > 0){
xState = FWD;
}else if(xAxis < 0){
xState = REV;
}
}else{
xState = STOP;
}
if(xState != lastTXxState){ //This makes the async TX data flow
xTX.xData = xState; //Cast the changed state to the TX callback
xRX.xData = xTX.xData; //This is an imaginary WiFi Link
char x_buf[20]; //Ignor the inverse logic it seems to be a bug
String ss = "";
if(xState == FWD){
ss = "X_REV";
}else if(xState == REV){
ss = "X_FWD";
}else{
ss = "X_STOP";
}
sprintf(x_buf,"Sending %s", ss);
Serial.println(x_buf); //Only prints when packet is sent
} //End Transmitter Logic
/* RX Logic Begins */
if(lastRXxState != xRX.xData){ //Won't hurt but may not be needed ????
char x_buf[20];
String ss = "";
if(xRX.xData == FWD){ //Receiver Motion Logic
stepper.setSpeed(50);
move = true;
}else if(xRX.xData == REV){
stepper.setSpeed(-50);
move = true;
}else if(xRX.xData == STOP){
move = false;
stepper.stop();
}
if(xRX.xData == REV){ //Ignor the inverse logic it seems to be a bug
ss = "X_FWD";
}else if(xRX.xData == FWD){
ss = "X_REV";
}else{
ss = "X_STOP";
}
sprintf(x_buf,"%s Received\n", ss);
Serial.println(x_buf); //Only prints when packet is reveived
}
if(move){
stepper.runSpeed();
} //End Receiver Logic
lastTXxState = xState; //For State engine of TX Logic
lastRXxState = xRX.xData; //For State engine of RX Logic
}