SERVO MOTOR INTERFACING WITH NODEMCU
A servo motor is an electric device used for precise control of angular rotation. It is used in applications that demand precise control over motion, like in case of control of the robotic arm.
The rotation angle of the servo motor is controlled by applying a PWM signal to it.
By varying the width of the PWM signal, we can change the rotation angle and direction of the motor. Mostly 50Hz PWM is used to control the shaft position of the servo motor.
For more information about Servo Motor and how to use it, refer to the topic Servo Motor in the sensors and modules section.
NodeMCU based ESP8266 can be used to control the servo motor. NodeMCU has a PWM feature on its GPIO, using which we can control servo motor.
Interfacing Servo Motor with NodeMCU
Controlling the position of a servo motor using a potentiometer.
Here, the potentiometer is used as a means for shaft position control of the servo motor. We can make use of the ADC feature of NodeMCU to read the potentiometer.
For servo motor, we are creating a 50Hz PWM signal on the D2 pin of NodeMCU. To control the servo motor shaft position within 180 degrees it is required to control its PWM duty cycle within 5% to 10%. We got some practical values of the PWM duty cycle which vary from 2.5% to 10.75% duty cycle to control the servo motor shaft position within 180 degrees.
We can write codes for NodeMCU DevKit in either Lua Script or C/C++ language. We are using ESPlorer IDE for writing code in Lua scripts and Arduino IDE for writing code in C/C++.
Arduino Sketch for servo
uint8_t ServoMotorpin = D2;
analogWriteFreq(50); /* Set PWM frequency to 50Hz */
uint16_t dutycycle= analogRead(A0); /* Read potentiometer to control servo motor */
if(dutycycle> 1023) dutycycle = 1023;
dutycycle = 25+((85*dutycycle/1023)); /* make it in range 20 to 110 */
analogWrite(ServoMotorpin, dutycycle); /* Write duty cycle to pin */
Also, Servo motor library comes along with the Arduino IDE with the ESP8266 package. To open the Servo example, go to File -> Examples -> Servo(esp8266) -> Sweep as shown in below image.
Change the servo pin as per application in the example sketch.