Servo motor control with PWM on PIC16F877A EN/ES

avatar
(Edited)

Greetings dear readers, after having learned about PWM we are ready to taste a little bit of robotics and mechatronics, these are areas that I am very passionate about and I can't help but feel excited to write about it.... well we are not going to do a robot or some mechatronics right now, however we are going to study a component that makes possible the connection between electronic engineering and mechanical engineering, these are the so called servo motors.

In this article we are going to know what servo motors are, their internal composition, working principle, applications, control and finally we are going to design a circuit to simulate it and get an illustration.


Saludos estimados lectores, luego de haber aprendido sobre PWM estamos listos para saborear un poco de robotica y mecatrónica, son áreas que me apasionan mucho y no puedo evitar sentirme emocionado al escribir sobre ello... bueno no vamos a hacer un robot o algo de mecatrónica ahora mismo, sin embargo vamos a estudiar un componente que hace posible la conexíon entre la ingeniería electrónica y la ingeniería mecánica, estos son los llamados servo motores.

En este artículo vamos a conocer lo que son los servo motores, su composición interna, principio de funcionamiento, aplicaciones, control y finalmente vamos a diseñar un circuito para simularlo y obtener así una ilustración.




Servo robot. Source: Pixabay

Defining a servo motor

Human beings have learned to use the different types of energy that nature gives us in our favor, technology is possible because we have taken advantage of the principles of energy transformation to obtain beneficial results and one of the most used is electrical energy which we have learned to convert it into almost any other type of energy.

Electronic engineering is precisely the branch that seeks to make this energy conversion possible in the most efficient way possible since it is in charge of designing the controls that shape the current both in the time and frequency domain to obtain satisfactory results.

Whenever I write I always try to use informal and easy to understand language, however we are already in a bit deep waters and given the amount of content I have posted I can assume that my readers already master many topics and terms, still I keep trying to make it as simple as possible, but effective 😉.

Now let's think about how to convert electrical energy into mechanical energy.... 🤔...

There are laws that define the behavior of electromagnetic fields, these fields are magnetic fields generated from electricity and we know that from a magnetic field can be obtained a mechanical force, so, although it is not the only way if it is the most used so we will focus on the electric motor.


Los seres humanos hemos aprendido a usar los diferentes tipos de energía que la naturaleza nos brinda a nuestro favor, la tecnología es posible porque hemos aprovechado los principios de transformación de energía para obtener los resultados benficiosos y una de las más usadas es la energía eléctrica la cual hemos aprendido a convertirla en casi cualquier otro tipo de energía.

La ingeniería electrónica es precisamente la rama que busca que esa conversión de energía se haga posible de la manera más eficiente posible ya que se encarga de diseñar los controles que le dan forma a la corriente tanto en el dominio del tiempo como en el de la frecuencia para obtener resultados satisfactorios.

Siempre que escribo trato de usar un lenguaje informal y de fácil comprensión, sin embargo ya estamos en aguas un poco profundas y dada la cantidad de contenido que he publicado puedo asumir que mis lectores ya dominan muchos temas y términos, aun así sigo intentando hacerlo lo más simple posible, pero efectivo 😉.

Ahora pensemos en cómo convertir energía electrica en energía mecánica... 🤔...

Existen leyes que definen el comportamiento de campos electromagnéticos, estos campos son campos magneticos generados a partir de electricidad y sabemos que de un campo magnético se puede obtener una fuerza mecánica, así que, aunque no es la única forma si es la más usada por lo cual nos centraremos en el motor eléctrico.




Wikimedia commons

Well, we have a motor, now we connect it to an electric power source and we all know what will happen (it will start to rotate 😄), we are producing mechanical energy but.... we already saw that it is possible to use PWM to control the revolutions, also for the case of AC motors we do the equivalent using TRIACs, but I don't want revolutions but precision turning movements, it would not be possible to achieve it with a common motor.

A servo motor is the combination of an electronic system (electrioc motor and control components) and a mechanical one (gear system) that make it possible to produce precision movements, unlike a conventional motor a servo motor does not keep turning, in fact it is rare that it makes a 360 degree turn, its movement is based on a controlled angle that can go from 0 to 180 degrees for closed loop motors and 0 to 360 for open loop motors.


Bien, tenemos un motor, ahora lo conectamos a una fuente de energía electrica y todos sabemos lo que pasará (comenzará a girar 😄), estamos produciendo energía mecánica pero... ¿qué tan controlada puede ser? ya vimos que es posible usar PWM para controlar las revoluciones, también para el caso de motores de alterna hacemos lo equivalente usando TRIACs, pero no quiero revoluciones sino movimientos de giro de precisión no sería posible lograrlo con un motor común.

Un servo motor es la combinación de un sistema electrónico (motor electrioc y componentes de control) y uno mecánico (sistema de engranajes) que hacen posible producir movimientos de precisión, a diferencia de un motor convencional un servo motor no se mantiene girando, de hecho es extraño que haga un giro de 360 grados, su movimiento está basado en un angulo controlado que puede ir de 0 a 180 grados para los motores de circuito cerrado y 0 a 360 para los de circuito abierto.




Position servo and signal flow graph. Author: Constant314, Source: Wikimedia Commons, License: CC0.

Internal composition and operation

Internally it is composed of an electric motor, a control system for the motor which is based on a comparator, this compares the value of the external control signal and the value of the current position angle and moves in one direction when necessary to maintain equality, the position angle is sent by a potentiometer, the position angle is proportional to the current that the potentiometer lets through and is used for feedback and control.

The gearing system allows converting a high speed, low torque motion at the motor to a low speed, high torque motion at the output. This determines the force that each motor can withstand which is usually written on the housing.

What this means is that once a command is sent for the servo to be in a position it will stay there and only a force higher than that can move it from that position, it can also overcome mechanical resistances lower than that value to get to that position. The servo position is determined by a PWM signal with specific characteristics (we will go into those details later).


Internamente está compuesto por un motor electrico, un sistema de control para dicho motor que se basa en un comparador, este compara el valor de la señal de control externa y el valor del angulo de posición actual y se mueve en un sentido cuando es necesario para mantener la igualdad, el angulo de posición es enviado por un potenciometro, el angulo de posición es proporcional a la corriente que dicho potenciometro deja pasar y se usa para la retroalimentación y control.

El sistema de engranajes permite convertir un movimiento de alta velocidad y bajo torque en el motor en uno de baja velocidad y alto torque en la salida. Esto determina la fuerza que puede soportar cada motor que generalmente está escrito en la carcaza.

Lo que esto representa es que una vez se envía un comando para que el servo esté en una posición se mantendrá ahí y solo una fuerza superior a esa lo puede mover de esa posición, también puede vencer resistencias mecánicas inferiores a ese valor para llegar a esa posición. La posición del servo es determinada por una señal PWM con características específicas (entraremos en esos detalles más adelante).




Author: WikiImages, Source: [Pixabay][https://pixabay.com/es/photos/marte-mars-rover-viaje-espacial-67522/], License: CC0.

Applications

The field of applications is so extensive that I dare to say that it is one of the few man-made devices that is currently operating on the planet Mars, the most used field is robotics and mechatronics so it would not be wrong to assume that the Robert Curiosity carries many of these in its mechanism.

This type of motors is useful for the movement of automatons in industrial factories, material handling, radio controlled airplanes, elevators, toys, aerospace industry, automobiles and many others (the limit is the imagination).


El campo de aplicaciones es tan extenso que me atrevo a decir que es uno de los pocos dispositivos hechos por el hombre que esta operando actualmente en el planeta Marte, el campo más usado es el de la robótica y mecatrónica por lo que no sería erroneo suponer que el Robert Curiosity lleva muchos de estos en su mecanismo.

Este tipo de motores es útil para el movimiento de automatas en fábricas industriales, manipulación de materiales, aviones radio controlados, ascensores, juguetes, industria aero espacial, automoviles y muchas otras (el límite es la imaginación).


Design and control with PIC16F877A

The servo motor is controlled by a PWM signal that must have a period of 20ms, this is a frequency of 50 Hz and means that every 20ms a pulse width is evaluated and the position of the motor is modified (if necessary) by a value that is determined by the pulse width.

Since we can generate PWM with a microcontroller we can take advantage of this fact to control servo motors. If we want the motor at the angle 0 degrees the pulse time should be 0.5ms, 1.5ms for 90 degrees and 2.5ms for 180 degrees, it is possible to use intermediate values between 0 and 180 and the only way to make the motor move is by the PWM signal or by overcoming its torque force (which is an undesired condition).

We will rely on a special library for servo motor control called <servo_st.c> that allows us to use any PIN of the microcontroller, it makes it as simple as defining the PIN you want to use and send the command for the desired position angle.


El servo motor es controlado por una señal PWM que debe tener un período de 20ms, esto es una frecuencia de 50 Hz y significa que cada 20ms se evalúa un ancho de pulso y se modifica (si es necesario) la posición del motor en un valor que está determinado por el ancho del pulso.

Ya que podemos generar PWM con un microcontrolador podemos aprovechar este hecho para controlar servo motores. Si deseamos el motor en el angulo 0 grados el tiempo del pulso debe ser de 0.5ms, 1.5ms para 90 grados y 2.5ms para 180 grados, es posible usar valores intermedios entre 0 y 180 y la única forma de hacer mover el motor es mediante la señal PWM o venciendo su fuerza de torque (que es una condición no deseada).

Nos apoyaremos en una librería especial para el control de servomotores llamada <servo_st.c> que nos permite usar cualquier PIN del microcontrolador, lo hace tan simple como definir el PIN que se desea usar y enviar el comando para el angulo de posición deseado.


Programming

To illustrate the servo motor control we will create a program in which we will use a potentiometer to give instructions about the servo motor positioning, the potentiometer will be connected to an ADC of the micro so it will be necessary to convert the 0-1023 signal to its equivalent 0-180 degrees and we will do this with the map function that we used and described in the previous article.

Using the dedicated library and the map function our code would be simplified as follows:


Para ilustrar el control del servo motor vamos a crear un programa en el que usaremos un potenciometro para dar instrucciones sobre el posicionamiento del servo motor, el potenciometro estará conectado a un ADC del micro por lo que será necesario convertir la señal de 0-1023 a su equivalente 0-180 grados y esto lo haremos con la función map que usamos y describimos en el articulo anterior.

Usando la librería dedicada y la función map nuestro código se simplificaría de forma siguiente:


#include <16f877a.h>

#device ADC = 10

#fuses HS,NOWDT,NOPROTECT,NOPUT,NOLVP,BROWNOUT

#use delay(clock=20M)

#use standard_io(D)

#define use_servo_1           

#define servo_1 PIN_D7        

#include <map_function.c

#include <servo_st.c
     

void main()

{

   setup_adc_ports(AN0);

   setup_adc(adc_clock_internal);

   servo_init();
   
   while(true)

   {

      set_adc_channel(0);

      delay_us(2);

      long adc_value = read_adc();

      int angle = map(adc_value, 0, 1023, 0, 180);

      servo_1_write(angle);

   }

}

Simulation

In our simulation we will move the potentiometer to evaluate how the motor moves, and we will also visualize the PWM signal on the oscilloscope.


En nuestra simulación vamos a mover el potenciometro para evaluar como se mueve el motor, además visualizaremos la señal PWM en el osciloscopio.











https://images.ecency.com/p/3W72119s5BjW4PvRk9nXBzqrPWMsMTjNrXDPFFf12CAfRz5MY8jCm5vGDUj7o96hwAT3YCMBJgcTgcWmsqeuBbZL1YbmxtaV4gyfByenDkmAkgv6rkm9ZP.webp?format=webp&mode=fit



0
0
0.000
9 comments
avatar

Congratulations @electronico! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You published more than 70 posts.
Your next target is to reach 80 posts.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Check out our last posts:

Our Hive Power Delegations to the January PUM Winners
Feedback from the February Hive Power Up Day
Hive Power Up Month Challenge - January 2023 Winners List
The Hive Gamification Proposal
0
0
0.000
avatar

I am making an effort, Mr. cyborg, this month I hope to go over 100!

0
0
0.000
avatar

¡Enhorabuena!


Has recibido el voto de PROYECTO CHESS BROTHERS

✅ Has hecho un buen trabajo, por lo cual tu publicación ha sido valorada y ha recibido el apoyo de parte de CHESS BROTHERS ♔ 💪


♟ Te invitamos a usar nuestra etiqueta #chessbrothers y a que aprendas más sobre nosotros.

♟♟ También puedes contactarnos en nuestro servidor de Discord y promocionar allí tus publicaciones.

♟♟♟ Considera unirte a nuestro trail de curación para que trabajemos en equipo y recibas recompensas automáticamente.

♞♟ Echa un vistazo a nuestra cuenta @chessbrotherspro para que te informes sobre el proceso de curación llevado a diario por nuestro equipo.


🥇 Si quieres obtener ganancias con tu delegacion de HP y apoyar a nuestro proyecto, te invitamos a unirte al plan Master Investor. Aquí puedes aprender cómo hacerlo.


Cordialmente

El equipo de CHESS BROTHERS

0
0
0.000
avatar

Congratulations your publication has been chosen among the best of the day.

KEEP CREATING GOOD CONTENT.

image.png

0
0
0.000