#include <Stepper.h>
#include <WiFi.h>
#include <ThingSpeak.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
WiFiClient client;
unsigned long myChannelNumber = 2041510;//2040482;//Factory Robo Lower Body
const char * myWriteAPIKey = "Y50XCTW02QJTTG5N";//"CHYKE5QV5QXQ312Q";
// ADC2 cannot work between esp_wifi_start() and esp_wifi_stop()... only ADC1 can
//LOWER BODY HORIZONDAL
int LBMotorPin = 32, LBMotorValue; // 32 is ADC1
int LBMotorStepPin = 12;
int LBMotorDirectionPin = 13;
int LBMotorSteps=5, LBMotorDegree=0, LBMotorMaxDegree=30;//30 is max
Stepper LBMotor(LBMotorSteps, LBMotorStepPin, LBMotorDirectionPin);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
LBMotor.setSpeed(100);
pinMode(LBMotorPin, INPUT);
pinMode(LBMotorStepPin, OUTPUT);
pinMode(LBMotorDirectionPin, OUTPUT);
}
void loop() {
/*
vertical -> 0 down 4095 up
horizondal -> 0 right 4095 left
*/
connectToCloud();
LBMotorValue = map(analogRead(LBMotorPin), 0, 4095, 1, -1);// right=1, left=-1, idle =0
LBMotorDegree = rotateMotor(LBMotor, LBMotorValue, LBMotorSteps, LBMotorDegree, LBMotorMaxDegree);
Serial.println(LBMotorDegree);
writeData();
}
int rotateMotor(Stepper motor, int pinValue, int steps, int degree, int maxDegree){
if(pinValue == 1) {
motor.step(steps);
if(degree < maxDegree)
degree += steps;
}
else if(pinValue == -1) {
motor.step(-steps);
if(degree > 0)
degree -= steps;
}
return degree;
}
void connectToCloud(){
if(WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass);
for(int i=0;i<5;i++) {
Serial.print(".");
delay(1000);
}
}
Serial.println("\nConnected.");
}
}
int statusCode;
void writeData() {
ThingSpeak.setField(1, 0);
ThingSpeak.setField(2, LBMotorDegree);
ThingSpeak.setField(3, 0);
statusCode = ThingSpeak.writeFields(myChannelNumber,myWriteAPIKey);
if(statusCode == 200) //successful writing code
Serial.println("Channel update successful.");
else
Serial.println("Problem Writing data. HTTP error code :" + String(statusCode));
//delay(1000); // data to be uploaded every 15secs
}