Here's the entire code, it it helps...
DEFINE OSC 20
OSCCON.4 = 1
OSCCON.5 = 1
OSCCON.6 = 1
'Define I/O pin names
motor_dir VAR PORTB.5 'Motor H-Bridge direction line
motor_pwm VAR PORTB.6 'Motor H-bridge pulse-width-modulation line
stop_button VAR PORTB.0 'Stop button on PORTB.0
brake1 VAR PORTB.2 'Brake on pin B.2
'Declare Variables
motor_speed VAR BYTE 'Motor speed as percentage of maximum (0 to 100)
motion_dir VAR BIT 'Motor direction (1:CW/Forward 0:CCW/Reverse)
on_time VAR WORD 'PWM ON pulse width
off_time VAR WORD 'PWM OFF pulse width
pwm_cycles VAR BYTE '# of PWM pulses sent during the position control loop
widthx VAR BYTE 'Name to store pulse value
run1 VAR BYTE
'Define Constants
pwm_period CON 50 'Period of each motor PWM signal cycle (in microsec)
CW CON 1 'Rotate the motor clockwise
CCW CON 0 'Rotate the motor counter clockwise
Pulse CON 50
'Initialize I/O and Variables
TRISB.6 = 0 'Configure H-bridge DIR pin as an output
TRISB.5 = 0 'Configure H-bridge PWM pin as an output
TRISB.1 = 1 'Configure input pulse pin as an input
TRISB.2 = 0 'Configure brake pin as an output
motion_dir = CW 'Starting motor direction: CW (forward)
motor_speed = 50 'Starting motor speed = 50% duty cycle
Low motor_pwm 'Make sure the motor is off to begin with
start:
pulsin PORTB.1,1,widthx
IF widthx >= 50 && widthx < 70 Then run_motor1
IF widthx >70 && widthx <90 Then Goto run_motor2
IF widthx >90 Then
Goto run_motor3
Else
Goto brake
Endif
Return
'Subroutine to run motor at the desired speed and direction
run_motor1:
Low Brake1
'Set the motor direction
motor_dir = CW
motor_speed = 50
'Output PWM signal
Gosub pwm_periods 'Calculate the on and off pulse widths
While (widthx >= 50 && widthx < 70)
Gosub pwm_pulse 'Send out a full PWM pulse
Wend
Goto start
run_motor2:
Low Brake1
'Set the motor direction
motor_dir = CCW
motor_speed = 70
'Output PWM signal
Gosub pwm_periods 'Calculate the on and off pulse widths
While (stop_button == 0) 'Until the stop button is pressed
Gosub pwm_pulse 'Send out a full PWM pulse
Wend
Goto start
run_motor3:
Low Brake1
'Set the motor direction
motor_dir = CW
motor_speed = 100
'Output PWM signal
Gosub pwm_periods 'Calculate the on and off pulse widths
While (stop_button == 0) 'Until stop button is pressed
Gosub pwm_pulse 'Send out a full PWM pulse
Wend
Goto start
'Subroutine to calculate the PWM on and off pulse widths based on the desired
'motor speed
pwm_periods:
'Be careful to avoid integer arithmetic
IF (pwm_period >= 655) Then
on_time = pwm_period/100 * motor_speed
off_time = pwm_period/100 * (100 - motor_speed)/100
Else
on_time = pwm_period*motor_speed/100
off_time = pwm_period*(100 - motor_speed)/100
Endif
Return
'Subroutine to output a full PWM pulse based on the data from pwm_periods
pwm_pulse:
'Send the ON pulse
High motor_pwm
Pauseus on_time
'Send the OFF pulse
Low motor_pwm
Pauseus off_time
Return
brake:
'brake motor
High brake1
Goto start




Bookmarks