MotorControl.h
#ifndef _MotorControl_H_
#define _MotorControl_H_
#include "S12PWM.h" // PWM variable definitions
void PWMinit(void);
/*Sets up the PWM frequency and sets motors to default duty cycle of zero*/
void LeftWheelForward(unsigned char DC);
/*Runs left wheel forwards at given duty cycle*/
void LeftWheelBackward(unsigned char DC);
/*Runs left wheel backwards at given duty cycle*/
void RightWheelForward(unsigned char DC);
/*Runs right wheel forward at given duty cycle*/
void RightWheelBackward(unsigned char DC);
/*Runs right wheel backward at given duty cycle*/
void StopRight(void);
/*Sets duty cycle of right wheel to zero*/
void StopLeft(void);
/*Sets duty cycle of left wheel to zero*/
#endif
MotorControl.c
#include "MotorControl.h"
#include <hidef.h> /* common defines and macros */
#include <mc9s12e128.h> /* derivative information */
#include <S12E128bits.h> /*E128 bit definitions */
#include <bitdefs.h> /* BIT0HI, BIT0LO definitions */
static const unsigned char PWMperiod = 200; // # of clock tics per PWM cycle
//~~~~~~~~~~~~~~ PWMinit ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void PWMinit(void)
{
//enable PWM
PWME = (PWME | _S12_PWME0 | _S12_PWME1 | _S12_PWME2 | _S12_PWME3);
//set prescale value 2
PWMPRCLK = (_S12_PCKA0 | _S12_PCKB0);
//set scale for clock SA & SB
PWMSCLA = 2;
PWMSCLB = 2;
//Select clock SA & SB
PWMCLK = (PWMCLK | (_S12_PCLK0 | _S12_PCLK1 | _S12_PCLK2 | _S12_PCLK3));
//Set Period
PWMPER0 = PWMperiod;
PWMPER1 = PWMperiod;
PWMPER2 = PWMperiod;
PWMPER3 = PWMperiod;
//Set default duty cycle to 0
PWMDTY0 = 0;
PWMDTY1 = 0;
PWMDTY2 = 0;
PWMDTY3 = 0;
//Map PWM to ports
MODRR = (_S12_MODRR0 | _S12_MODRR1 | _S12_MODRR2 | _S12_MODRR3);
//set polarity
PWMPOL = (_S12_PPOL0 | _S12_PPOL1 | _S12_PPOL2 | _S12_PPOL3);
return;
}
//****** Left Wheel Forward ******//
void LeftWheelForward(unsigned char DC)
{
PWMDTY0 = 0; // 0%
PWMDTY1 = DC * PWMperiod/100; // 50%
return;
}
//****** Left Wheel Backward ******//
void LeftWheelBackward(unsigned char DC)
{
PWMDTY0 = DC * PWMperiod/100; // 50%
PWMDTY1 = 0; // 0%
return;
}
//****** Right Wheel Forward ******//
void RightWheelForward(unsigned char DC)
{
PWMDTY2 = 0; // 0%
PWMDTY3 = DC * PWMperiod/100; // 50%
return;
}
//****** Right Wheel Backward ******//
void RightWheelBackward(unsigned char DC)
{
PWMDTY2 = DC * PWMperiod/100; // 50%
PWMDTY3 = 0; // 0%
return;
}
//****** Stop Right ******//
void StopRight(void)
{
PWMDTY2 = 0; // 0%
PWMDTY3 = 0; // 0%
return;
}
//****** Stop Left ******//
void StopLeft(void)
{
PWMDTY0 = 0; // 0%
PWMDTY1 = 0; // 0%
return;
}