Skip to content

Instantly share code, notes, and snippets.

@LukeGary462
Created March 19, 2021 22:21
Show Gist options
  • Select an option

  • Save LukeGary462/055b71ee5116ce0221790fb22fbcd893 to your computer and use it in GitHub Desktop.

Select an option

Save LukeGary462/055b71ee5116ce0221790fb22fbcd893 to your computer and use it in GitHub Desktop.
MAX14871 Motor Driver Arduino Class
#include <Arduino.h>
class Max14871 {
public:
Max14871(uint8_t pwm_pin, uint8_t dir_pin);
void init(unsigned int pwm_freq);
void set_duty_cycle(float duty);
void set_speed(float speed);
void enable(void);
void disable(void);
private:
uint8_t _pwm_pin;
uint8_t _dir_pin;
unsigned int default_pwm_freq_hz = 20000u;
unsigned int max_pwm_code = 0xFFFF;
uint8_t pwm_res_bits = 16u;
void config_pwm(unsigned int freq);
};
/**
* constructor
*/
Max14871::Max14871(uint8_t pwm_pin, uint8_t dir_pin) {
this->_pwm_pin = pwm_pin;
this->_dir_pin = dir_pin;
}
/**
* init pins and PWM timer
* @param {uint} unsigned int pwm_freq pwm frequency in Hz
* @return {none} none
*/
void Max14871::init(unsigned int pwm_freq) {
pinMode(this->_pwm_pin, OUTPUT);
this->config_pwm(pwm_freq);
this->enable();
}
/**
* sets duty cycle on DIR pin
* @param {float} float duty duty cycle from 0.0 - 1.0
*/
void Max14871::set_duty_cycle(float duty) {
if (duty > 1.0f)
duty = 1.0f;
else if (duty < 0.0f)
duty = 0.0f;
unsigned int output = \
(unsigned int)((float)duty*(float)this->max_pwm_code);
analogWrite(this->_dir_pin, output);
}
/**
* set speed from -1.0 to 1.0
* @param {float} float speed normalized angular velocity of motor
*/
void Max14871::set_speed(float speed){
if (speed < -1.0)
speed = -1.0;
if (speed > 1.0)
speed = 1.0;
float duty = (speed * 0.5) + 0.5;
this->set_duty_cycle(duty);
}
/**
* enable output, PWM pin on driver used as enable
*/
void Max14871::enable(void) {
digitalWrite(this->_pwm_pin, 1);
}
/**
* disable output, PWM pin on driver used as enable
*/
void Max14871::disable(void) {
digitalWrite(this->_pwm_pin, 0);
}
/**
* set pwm frequenct
* @param {uint} unsigned int freq freq in Hz
* @return {none} none
*/
void Max14871::config_pwm(unsigned int freq) {
if (freq < 0)
freq = 1;
else if (freq > 70000)
freq = 70000;
analogWriteResolution(this->pwm_res_bits);
analogWriteFrequency(freq);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment