Archivo de microcontrolador

Controlando un servo con PWM, PICmicro y C

Posted in electronica with tags , , , on 1 marzo 2010 by Rubén

Jurrr, y buscando videos mios en youtube me encuentro con este otro vídeo que habia olvidado, controlando un servo (trucado de ahi los giros de 360 grados) con un microcontrolador PIC programado en C, compilado con CSS.

//***********************************************************************************
//
//       Programa. Generador pulsos PWM
//       Descripción. Generador de pulsos PWM para
//       controlar un servo motor. Cristal 4Mhz. El servo gira a derecha si PIN_A0=0 y PIN_A1 =1
//       y a izquierdas si PIN_A0=1 y PIN_A1 =0 en ambos casos con resolucion 12.96. Si no se
//       cumplen estas condiciones el servo permanece en posición STOP
//       Autor. N4v4jo/Atsea
//       Fecha. 05/04/06
//
//************************************************************************************

#include <16F877A.h>
#define SERVO PIN_C2
#use delay(clock=4000000)

void MoveServo (int Direction);

/*—————— Main Program ——————–*/

void main(void)
{
while (1)
{
if ((input(PIN_A0)==1) && (input(PIN_A1)==0))    //if pin RA0=1 and RA1=0 turn left
MoveServo(1);

if ((input(PIN_A0)==0) && (input(PIN_A1)==1))    //if pin RA0=1 and RA1=1 turn right
MoveServo(3);

if ((input(PIN_A0)==0) && (input(PIN_A1)==0))    //if pin RA0=0 and RA1=0 stop
MoveServo(2);
}
}

/*——————– FUNCTIONS ———————*/

void MoveServo (int Direction)    // values for Direction 1 to 3
{
int i;

if (Direction == 1) // move to the left
{
// generate a pwm with period of 20ms and a pulse with 1ms
for (i = 0; i < 50; i++)
{
output_high (SERVO);
delay_ms (1);
output_low (SERVO);
delay_ms (19);
}
}

if (Direction == 2) // move to the center
{
// generate a pwm with period of 20ms and a pulse with 1,5ms
for (i = 0; i < 50; i++)
{
output_high (SERVO);
delay_ms (1);
delay_us (500); // note this is microseconds

output_low (SERVO);
delay_ms (18);
delay_us (500);
}
}

if (Direction == 3) // move to the right
{
// generate a pwm with period of 20ms and a pulse with 2ms
for (i = 0; i < 50; i++)
{
output_high (SERVO);
delay_ms (2);

output_low (SERVO);
delay_ms (18);
}
}

return;
}

… y lo mismo con Arduino en cuatro líneas de código… bendito Arduino!.