#include <Stepper.h>
#include <WiFi.h>
#include <ThingSpeak.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
WiFiClient client;
unsigned long myChannelNumber = 2094306;//2040649;//Factory Robo Lower Body
const char * myWriteAPIKey = "ZRBV60DUF64ZJBOM";//"7S9LCNUGGNLF62LJ";
// ADC2 cannot work between esp_wifi_start() and esp_wifi_stop()... only ADC1 can
//LOWER BODY HORIZONDAL
int UBMotorPin = 32, UBMotorValue; // 32 is ADC1
int UBMotorStepPin = 12;
int UBMotorDirectionPin = 13;
int UBMotorSteps=5, UBMotorDegree=0, UBMotorMaxDegree=15;//15 is max
Stepper UBMotor(UBMotorSteps, UBMotorStepPin, UBMotorDirectionPin);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
UBMotor.setSpeed(100);
pinMode(UBMotorPin, INPUT);
pinMode(UBMotorStepPin, OUTPUT);
pinMode(UBMotorDirectionPin, OUTPUT);
}
void loop() {
/*
vertical -> 0 down 4095 up
horizondal -> 0 right 4095 left
*/
connectToCloud();
UBMotorValue = map(analogRead(UBMotorPin), 0, 4095, 1, -1);// right=1, left=-1, idle =0
UBMotorDegree = rotateMotor(UBMotor, UBMotorValue, UBMotorSteps, UBMotorDegree, UBMotorMaxDegree);
Serial.println(UBMotorDegree);
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);
Serial.print(".");
delay(5000);
}
}
Serial.println("\nConnected");
}
int statusCode;
void writeData() {
ThingSpeak.setField(1, 0);
ThingSpeak.setField(2, 0);
ThingSpeak.setField(3, UBMotorDegree);
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
}