Motor driver library for the AP1017.
AKM Development Platform
AP1017 Motor Driver
Import libraryAP1017
Motor driver library for the AP1017.
AP1017.cpp
- Committer:
- tkstreet
- Date:
- 2017-04-17
- Revision:
- 1:4d4c77589134
- Parent:
- 0:a0435a630c5d
- Child:
- 3:f8e70f639ed0
File content as of revision 1:4d4c77589134:
#include "AP1017.h" /******************** Constructors & Destructors ****************************/ // Default constructor AP1017::AP1017(void) : motorOn(false), dutyCycle(0.0), freq_hz(0.0), pulseWidth_us(0.0), pwmPeriod_us(0.0) { motor = NULL; inA = NULL; inB = NULL; } // Default destructor AP1017::~AP1017(void) { stopMotor(); delete inA, inB, motor; } /*********************** Member Functions ***********************************/ AP1017::Status AP1017::setDirection(char dir) { switch(dir){ case DIRECTION_CW: if(motorOn == true && dir == DIRECTION_CCW) return ERROR_MOTORON; inA->write(1); inB->write(0); motorOn = true; break; case DIRECTION_CCW: if(motorOn == true && dir == DIRECTION_CW) return ERROR_MOTORON; inA->write(0); inB->write(1); motorOn = true; break; case DIRECTION_BRAKE: inA->write(1); inB->write(1); motorOn = true; break; case DIRECTION_COAST: inA->write(0); inB->write(0); motorOn = false; break; default: return ERROR_DIRECTION; } return SUCCESS; } AP1017::Status AP1017::setDutyCycle(float dc) { if((dutyCycle <= 1.00) && (dutyCycle >= 0.0)){ dutyCycle = dc; pulseWidth_us = dutyCycle * pwmPeriod_us; // Override pulse width if(motorOn == true){ motor->write(dutyCycle); // If motor is on, keep it on } } else{ dutyCycle = 0.0; pulseWidth_us = 0.0; return ERROR_DUTY_CYCLE; } return SUCCESS; } AP1017::Status AP1017::setFrequency(float freq) { if(freq > MAX_FREQUENCY){ return ERROR_FREQUENCY; } freq_hz = freq; pwmPeriod_us = (1/freq)/0.000001; // Calculate the period return SUCCESS; } AP1017::Status AP1017::setPeriod_us(float per) { if(per < 0){ return ERROR_PERIOD; } pwmPeriod_us = per; freq_hz = 1/(per * 0.000001); // Calculate the frequency if(motorOn == true){ // If motor on, keep it on motor->period_us(pwmPeriod_us); } return SUCCESS; } AP1017::Status AP1017::setPulseWidth_us(float pw) { if((pw <= 0.0) || (pw > pwmPeriod_us)){ return ERROR_PULSEWIDTH; } dutyCycle = pw/pwmPeriod_us; // Override duty cycle pulseWidth_us = pw; return SUCCESS; } AP1017::Status AP1017::startMotor(void) { motor->period_us(pwmPeriod_us); // Set the period motor->pulsewidth_us(pulseWidth_us); // Set the pulse width motor->write(dutyCycle); // Set duty cycle, start motor motorOn = true; // Set ON flag return SUCCESS; } AP1017::Status AP1017::stopMotor(void) { motor->write(0.0); // turn motor off (duty cycle saved) motorOn = false; // Set OFF flag return SUCCESS; } AP1017::Status AP1017::brakeMotor(void) { setDirection(DIRECTION_BRAKE); return SUCCESS; } AP1017::Status AP1017::coastMotor(void) { setDirection(DIRECTION_COAST); return SUCCESS; }