Hi! I am trying for 3 days to control basic servo motor (sg90) by using Pic16f877a by Timer0 in Mplab XC8 compiler.
I wrote this code based on my calculations which I attached. However, while it must give 90 degree, it always gives 180 degree in Proteus simulation and it doesn't work in real microcontroller also. However, when I tried with overflow time of 0.2ms I could get correct values for degrees of 0, 90, 45, 180. However, by value of 0.2ms I cannot get all of the values. Please, can you help me why it doesn't work? Am I miscalculating something?
Code:
#include <xc.h>
#include <stdint.h>
#include "config.h"
#define _XTAL_FREQ 6000000
uint16_t counter = 0;
uint16_t on_time = 281, pwm_period_time = 3750;
void main(void) {
TRISD = 0x00;
PORTD = 0x00;
PSA = 0;
TMR0 = 252;
T0CS = 0;
//Prescaler
PS0 = 0;
PS1 = 0;
PS2 = 0;
TMR0IE = 1;
TMR0IF = 0;
PEIE = 1;
GIE = 1;
while(1);
}
void __interrupt() ISR()
{
if(TMR0IF)
{
TMR0IF = 0;
TMR0 = 252;
//PORTDbits.RD0 = ~PORTDbits.RD0;
if(counter == 0)
{
PORTDbits.RD0 = 1;
}
if(counter == on_time)
{
PORTDbits.RD0 = 0;
}
counter++;
if(counter == pwm_period_time)
{
counter = 0;
}
}
}
Attachments
-
62.8 KB Views: 10