NodeMCU Servo WIFI

 #include <Servo.h>
#include <ESP8266WiFi.h>            
#include <ESP8266WebServer.h>

ESP8266WebServer server(80);   //Web server object. Will be listening in port 80 (default for HTTP)

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {

    myservo.attach(14);  // attaches the servo on GIO2 to the servo object
    
    Serial.begin(115200);
    WiFi.begin("DIGI-N8mK", "abcde#12345"); //Connect to the WiFi network
    
    while (WiFi.status() != WL_CONNECTED) { //Wait for connection
      delay(500);
      Serial.println("Waiting to connect…");
    }
    
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());  //Print the local IP to access the server
    
    server.on("/servo", handleCall);   //Associate the handler function to the path
    
    server.begin();                                       //Start the server
    Serial.println("Server listening");   

}

void loop() {

    server.handleClient();    //Handling of incoming requests

}

void handleCall() {

    String angle;
    angle = server.arg("angle");

    int intangle;
    intangle = angle.toInt();

    if(intangle < 20){
     intangle = 20;
    }else if(intangle > 93){
      intangle = 93;
    }

   servoControl(intangle);
    
   server.send(200, "application/json", "{\"angle\":"+ angle +"}"); //Returns the HTTP response

}

void servoControl(int new_angle){

    int old_angle = myservo.read();

    // Works fine
    if(new_angle > old_angle){

       for (pos = old_angle; pos <= new_angle; pos += 1) { // goes from 0 degrees to 180 degrees
          // in steps of 1 degree
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          delay(20);                       // waits 15ms for the servo to reach the position
        }

      
    }else if(new_angle < old_angle){

        for (pos = old_angle; pos >= new_angle; pos -= 1) { // goes from 180 degrees to 0 degrees
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          delay(20);                       // waits 15ms for the servo to reach the position
        }

    }
 
}


// serial print variable type
void types(String a) { Serial.println("it's a String"); }
void types(int a) { Serial.println("it's an int"); }
void types(char *a) { Serial.println("it's a char*"); }
void types(float a) { Serial.println("it's a float"); }
void types(bool a) { Serial.println("it's a bool"); }

Comments

Popular posts from this blog

Laravel Reverb + Echo naming convention.