bblanchon / ArduinoContinuousStepper

An Arduino library to spin stepper motors in continuous motions.
MIT License
39 stars 4 forks source link

Use of PWM #11

Closed dinther closed 1 year ago

dinther commented 1 year ago

First of all thank you for writing this nice library. It is exactly what I needed and it works beautifully on my Raspberry Pico with 3 steppers powered by TMC2209 drivers.

While working, I wondered if it is possible to use PWM with a variable frequency to drive the step input from my TMC2209 drivers. for this I found this library: https://github.com/khoih-prog/RP2040_PWM

Any micro controller with adjustable PWM frequency can be used but the Raspberry Pico is particularly good at it and offers 8 hardware PWM channels each with a frequency ranging from 7.5Hz to 120MHz (Yeah that is a bit fast lol)

It was easy enough to try and I can confirm it works. I simply used a duty cycle of 50% (Recommended by Trinamic) I am not aware of anyone who has even done this with PWM and I might find reasons why you would not want to do this. I thought maybe this idea is of some use to you.

#include <RP2040_PWM.h>

RP2040_PWM* stepper;
float frequency;
float dutyCycle;
#define STEP_PIN      8
#define DIR_PIN       9

void setup() {
  pinMode(DIR_PIN, OUTPUT);
  //  Create PWM object and passed just a random frequency of 500 in it
  //  The duty cycle is how you turn the motor on and off
  stepper = new RP2040_PWM(STEP_PIN, 500, 0);
}

void loop() {
  setSpeed(1000);
  delay(3000);
  setSpeed(-500);
  delay(3000);
}

void setSpeed(int speed){
  //  Set the frequency of the PWM output and a duty cycle of 50%
  digitalWrite(DIR_PIN, (speed < 0));
  stepper->setPWM(STEP_PIN, abs(speed), 50);  
}
bblanchon commented 1 year ago

Hi @dinther,

I thought of this too, but I didn't dare to try 😄. Indeed, PWM is widely available and would offload the CPU.

I'm pretty busy at the moment, but I'll work on this as soon as I can.

Best regards, Benoit

bblanchon commented 1 year ago

I added the ContinuousStepper_KhoiH class on version 2.2.0. It should work on all Khoi Hoang's PWM libraries, but I only tested it on Teensy.

Here is the code you'd use for RP2040:

#include <ContinuousStepper_KhoiH.h>
#include <RP2040_PWM.h>

const uint8_t stepPin = 2;
const uint8_t dirPin = 3;

ContinuousStepper_KhoiH<RP2040_PWM> stepper;

void setup() {
  stepper.begin(stepPin, dirPin);
  stepper.spin(200);
}

void loop() {
  stepper.loop();
}

You still need to call stepper.loop() periodically to let the library update the speed.