Hello all, i am working on a simple DC motor control in 1 direction only. I will attach the code written in HITECH C Compiler for PIC16F887.
I Connected the circuit, and the motor is rotating for 2 seconds, stops for 2 seconds, and then rotates again for 2 seconds but i can't feel any difference in its rotation speed ! Help. Thank You
Rich (BB code):
#include <htc.h>
#include <stdlib.h>
#define _XTAL_FREQ 8000000
#define TMR2_PRESCALER 4
__CONFIG(0x28C4); // config word 1
__CONFIG(0x3eff); // config word 2 (in sequence)
#define byte unsigned char
#define word unsigned int
#define dword unsigned long
typedef union _word_VAL
{
word Val;
struct { byte LB; byte HB; } byte1;
} word_VAL;
byte x1,x2,x3,speed;
byte ccpr1l_copy,ccpr2l_copy;
void PWM1_Init(word x),PWM1_Set_Duty(byte x),PWM1_Start(),PWM1_Stop();
void PWM2_Init(word x),PWM2_Set_Duty(byte x),PWM2_Start(),PWM2_Stop();
void init();
void Move_Forward(int speed);
void Clutch();
void main()
{
init();
while(1)
{speed=1;
Move_Forward(speed);
__delay_ms(2000);
Clutch();
__delay_ms(2000);
speed=3;
Move_Forward(speed);
__delay_ms(2000);
Clutch();
__delay_ms(2000);
}
} // End main program
void init()
{
OSCCON=0b01110001; //frequency = 8M
ANSEL=0b1110000; //Enable PortA Analog Input,AN4,AN5,AN6
ANSELH=0; //Disable PortB Analog Input
C1ON=0; //turn off
C2ON=0; //comparators
TRISA=0b11110000; //RA0,RA1,RA2,RA3 Digital Outputs for stepper motor of Camera,AN4 Analog Input for Light Sensor
TRISB=0b11101011; //RB2,RB4 Digital Outputs for Horn and Flashlight
TRISC=0b11110000; //RC0,RC3 Digital Outputs for DC motor, CCP1,CCP2 for PWM Output
TRISD=0b11000000; //RD0,RD1,RD2,RD3 Digital Outputs for stepper motor of Robot ,RD4 Digital Output for Camera,RD5 Digital Output for Clutch
T2CON=0b00000001; // prescaler=4
CCP1CON=0b00001100;
CCP2CON=0b00001100;
CCPR1H=CCPR1L=CCPR2H=CCPR2L=0;
ccpr1l_copy=ccpr2l_copy=0;
PWM1_Init(5000); //Initialize PWM modules at
PWM2_Init(5000); //5KHz frequency
RCSTA=0b10010000;
TXSTA=0b00100100;
BAUDCTL=0b00000000;
SPBRG=207;
}
void Move_Forward(int speed)
{ byte current_duty;
switch(speed)
{ case 1:
current_duty = 20;
break;
case 2:
current_duty = 127;
break;
case 3:
current_duty = 240;
break;
case 0:
RC0=0;
PWM1_Stop();
break; }
if (current_duty!=0)
{PWM1_Set_Duty ( current_duty );
PWM1_Start();
RC0=1; }
}
void Clutch()
{ RD5=1;
RC0=0;
RC3=0;
PWM1_Stop();
PWM2_Stop();
}
void PWM1_Init(word x)
{
PR2=((_XTAL_FREQ/(4*TMR2_PRESCALER))/x)-1;
}
void PWM1_Set_Duty(byte x)
{
ccpr1l_copy=x*(PR2+1)/100;
}
void PWM1_Start()
{
CCPR1L=ccpr1l_copy;
}
void PWM1_Stop()
{
CCPR1L=0;
}
void PWM2_Init(word x)
{
PR2=(500000/x)-1;
}
void PWM2_Set_Duty(byte x)
{
ccpr2l_copy=x*(PR2+1)/100;
}
void PWM2_Start()
{
CCPR2L=ccpr2l_copy;
}
void PWM2_Stop()
{
CCPR2L=0;
}