# Controlling Stepper Speed with MATLAB + Arduino

81 views (last 30 days)
Luke G. on 4 Sep 2020
Edited: Luke G. on 17 Nov 2020
To keep things short & sweet...
• Motive: I want to control the rotational speed of my stepper motor using MATLAB. Why? Cause there's also some stuff I want to plot while it runs in MATLAB.
• Hardware: stepper motor + driver + Arduino
• Problem: MATLAB has only a few controls for Arduino PWM: writePWMVoltage, writePWMDutyCycle
• Solution Needed: I need a way to control the shape of the square wave to control the stepper speed--i.e., frequency, duty cycle, and even peak would be great
The wave needs to bounce between high (5V) or low (0V) with a 50% duty cycle, but user-control over the frequency (e.g., freq = 1/pulseDelay).
So what are some clever ways to do this?
Approach 1: One is to set up a while loop in which you manually send a pulse every pulseDelay seconds. However, you reach a limit in communication speed between MATLAB and the Arduino (e.g., no speed change between pulseDelay = 1E-3 and pulseDelay = 1E-6). It also moves way too slow.
writePWMVoltage(a,'D9',5); % set direction, CCW
delay = 1E-6; % time between steps, [s]
while 1
writePWMVoltage(a,'D10',5); % take one step
pause(delay) % pause
writePWMVoltage(a,'D10',0); % take one step
pause(delay) % pause
end
Approach 2: Create a square wave function and try to get writePWMVoltage to write it. This doesn't work, as this function only takes scalar double between 0 and 5.
writePWMVoltage(a,'D9',5); % set direction
time = 0:0.1:60;
sqrWave = 2.5*(square(time)+1);
for count = 1:length(time)
writePWMVoltage(a,'D10',sqrWave);
end
Approach 3: The only thing that works smoothly: writePWMDutyCycle, but I have no control over speed which is what I really want. OR at least to know what speed I'm going at while this line of code executes...
while 1
writePWMDutyCycle(a, 'D10', 0.5); % PWM signal with 50% duty cycle
end
Suggestions are very welcome! I'd love to use MATLAB for this task, but if the support, functions, documentation, etc. are not there for this project that's fine--I'll switch back to Arduino.
##### 2 CommentsShowHide 1 older comment
Luke G. on 17 Nov 2020
Lucas, sorry - I ended up just sticking with Approach 3 because it was the most reliable and speed isn't absolutely critical to my application. Though I would love to know if you (or anyone else) figures it out! Cheers

Sign in to comment.

R2020a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!