Analog Motor Control using PWM-to-DC conversion

I had originally thought the BA6886N motor controller required DC to control motor speed, which it can, but then I found that I can pulse the direction pins with PWM which eliminated the need for the active low pass filter. For reference I’ve moved the analog filter approach to this page.

Here is the code that runs the motor controller:

int pin = 13;
volatile int state = LOW;
volatile int lastTime = 0;

int last = 0;
int writeTime = 0;
int delta = 0;

#define BUFSIZE 200
char buf[BUFSIZE];

void setup()
{
  Serial.begin(9600);
  pinMode(pin, OUTPUT);
  attachInterrupt(0, blink, RISING);
  pinMode(1, OUTPUT);
}

void loop()
{
  int curr = millis();
  if (last != lastTime) {
    int tmp = lastTime - last;
    if (tmp > 30) {
      delta = tmp;
    }
    last = lastTime;
  }
  else if ((curr - lastTime) > 3000) {
    delta = 0;
  }  

  if ((curr - writeTime) > 1000) {
    int a = analogRead(0);
    analogWrite(3, a / 4);

    float d = delta;
    float result = 0;
    if (d > 0)
      result = 10000 / d;

    String msg = "Delta: ";
    msg += delta;
    msg += " Speed: ";
    msg += (int)result;
    msg += " A: ";
    msg += a;
    msg += "\n";
    msg.toCharArray(buf, BUFSIZE); 
    Serial.write(buf);
    writeTime = curr;
  } 
  digitalWrite(pin, state);
}

void blink()
{
  lastTime = millis();

  state = !state;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>