Below is the code for my project. The attachment is the schematic.
- CODE: SELECT_ALL_CODE
//Project: Servo Motor
//PIC: PIC16F877A
//Crystal Frequency: 20MHz
#include <pic.h>
#include <htc.h>
__CONFIG(0x3F32);
#define SERVO RC0
#define min 10
#define max 50
#define _XTAL_FREQ 20000000
void pic_init(void);
void timer_init(void);
int read_a2d(unsigned char channel);
int counter,position;
static void interrupt isr(void)
{
if(TMR0IF==1){
TMR0IF=0;
counter++;
if(counter==position) SERVO=0;
if(counter==390){
counter=0;
SERVO=1;}
}
}
main()
{int i;
pic_init(); //initialize PIC
timer_init(); //initialize Timer Module
for(;;){
position=0.9775*(max-min)*read_a2d(0)/1000+min; //change ADC voltage value to position
}}
void pic_init(void)
{
TRISA=0b00000001;
TRISB=0b00000000;
TRISC=0b00000000;
TRISD=0b00000000;
TRISE=0b00000000;
ADCON1=0b00000110; //configures the functions of the port pins
PORTA=0b00000000;
PORTB=0b00000000;
PORTC=0b00000000;
PORTD=0b00000000;
PORTE=0b00000000;
INTCON=0b10100000; //Enable Global, TMR0 Interrupt
PIE1=0b00000000; //Disable TMR1, TMR2 Interrupt
PIE2=0b00000000;
}
void timer_init(void)
{
OPTION_REG=0b00001000; //Internal instruction clock
T1CON=0b00000000; //Timer1 OFF
T2CON=0b00000000; //Timer2 OFF
PR2=255;
TMR0=0;
TMR1H=0;
TMR1L=0;
TMR2=0;
}
int read_a2d(unsigned char channel)
{ADCON0=0b00000001; //Turn on A/D module
ADCON1=0b10000000; //configures analog and voltage reference pins
ADCON0=(ADCON0&0xC7)|(channel<<3); //select analog input channel
__delay_ms(2);
ADON=1; //initiate conversion on the selected channel
while(ADON==1) continue; //wait until conversion done
return(256*ADRESH+ADRESL);}
The code has been successfully compiled and loaded into PIC. The potentiometer is connected to ground, 5V and RA0. Servo is connected to 5v, ground and RC0. According to my code, the servo should be rotating while I rotate the potentiometer. However, the servo doesn't rotate. The servo rotates once I connect it to 5V and then stop. Could someone please help me to check my code.
Thanks!!