servo.c

PIC16F877 code that demonstrates servo control (by James Gaston).




/************************************************/

/* servo.c                                      */

/*  Servo test program for 16F877               */

/*                                              */

/* By James Gaston                              */

/*                                              */

/* Servo control: PORTC[0]                      */

/* This program demonstrates servo control using*/

/* an '877.  The servo will sweep from the 180  */

/* degree position to 0 degrees and back, like  */

/* a sprinkler.                                 */

/*----------------------------------------------*/



#include <system.h>



//Configuration Bits

asm

{

list p=16F877

__config H'3D3A'

}//No WDT,No PUPT,No LVT, HS Oscillator



#pragma CLOCK_FREQ 20000000



#define T0IF_Mask 0x04

#define RC0 0



//Variables

short period_counter; //20 ms perdiod for servo control

char PW_counter;  // Pulse Width: 1-2ms

char position;  // Sets the position of the servo 0x32 = 180 deg, 0x0A = 0 deg (approx.)



void interrupt(void)

{

    //TMR0 Interrupt

    if (T0IF_Mask & intcon)

    {

        if (PW_counter <= position)

        {

            set_bit(portc,RC0);

            PW_counter=PW_counter+1;

        }

        else

            clear_bit(portc,RC0);

        period_counter++;

        if(period_counter == 400)

        {

            period_counter=0;

            PW_counter=0;

        }

        tmr0 = 5;

        clear_bit(intcon,T0IF);

    }//TMR0 Interrupt

}

main()

{

    //SETUP

    option_reg = 11001111b; //Timer Setup

    trisc = 11111110b; //PortC Configuration



    //INITIALIZATION

    tmr0 = 5;

    position=40;

    period_counter=0;

    PW_counter=0;



    //ENABLE INTERRUPTS

    enable_interrupt(T0IE);

    enable_interrupt(PEIE);

    enable_interrupt(GIE);



    //Main Loop

    while(1)

    {

        position = position - 1;

        if(position == 10)

        {

            position=50;

            delay_ms(750);

        }

        delay_ms(50);

    }

}






http://www.sourceboost.com/home.html

Copyright © 2002-2006 SourceBoost Technologies