- CODE: SELECT_ALL_CODE
#include <p18f4550.h>
#include <delays.h>
//define RUN pins
#define RUN1 PORTDbits.RD1
#define RUN2 PORTDbits.RD2
//define CCW pins
#define CCW1 PORTDbits.RD0
#define CCW2 PORTDbits.RD3
//define PWM pins
#define PWM1 CCPR1L //PIN RC2
#define PWM2 CCPR2L //PIN RB3
// motor subroutine
void setup(void);
void setup_pwm (void);
void motors (unsigned char, unsigned char, char, char);
void brake (void);
void turnleft (void);
void turnright (void);
//setup motors subroutine
void setup (void)
{
TRISBbits.TRISB3 = 0; //PWM2
TRISCbits.TRISC2 = 0; //PWM1
TRISDbits.TRISD0 = 0; //CCW1
TRISDbits.TRISD1 = 0; //RUN1
TRISDbits.TRISD2 = 0; //RUN2
TRISDbits.TRISD3 = 0; //CCW2
RUN1 = 1; //break motor 1
CCW1 = 1; //motor1 rotate in countclockwise
PWM1 = 0; //clear motor 1 PWM
RUN2 = 1; //break motor 2
CCW2 = 0; //motor2 rotate in clockwise
PWM2 = 0; //clear motor 2 PWM
}
//setup pwm (pulse width modulation) for motors
void setup_pwm (void)
{ //find 100 PR2, decimal = 100: hex = 0x64
PR2 = 0x64; //20.2 usec (20MHz osc) 49.5kHz (1 int period(4 cycle of clock) > calc 256 period > freq of 256 period)
CCP1CON = 0x0C; //b'00001100' PWM1 activated
CCP2CON = 0x0C; //PWM2 activated
T2CON = 0x04; //b'00000100; TMR2 ON, Postscale 1:1, Prescaler = 1
}
// motors control subroutine
void motors (unsigned char speed1, unsigned char speed2, char direction1, char direction2)
{ //motor 1 = left motor :: motor 2 = right motor
//examples : motors (200,200,1,1); move robot forward
// motors (200,200,0,0); move robot backward
//declare motor speed
PWM1 = speed1;
PWM2 = speed2;
//declare motors rotate direction
if (direction1 == 0) //setup motor1 direction
CCW1 = 0;
else
CCW1 = 1;
if (direction2 == 0) //setup motor2 direction
CCW2 = 1;
else
CCW2 = 0;
RUN1 = 0; //run motor1
RUN2 = 0; //run motor2
}
//brake motors subroutine
void brake (void) //brake both motors
{
//brake motors instatenously
//example : brake();
RUN1 = 1;
RUN2 = 1;
Delay10KTCYx(9); //delay 10 ms for next command
}
void turnleft (void)
{
motors (100,100,0,1);
}
void turnright (void)
{
motors (100,100,1,0);
}