Motor control using keyboard, Matlab and Arduino+shield

4 views (last 30 days)
My goal is to control a DC motor by pressing pc keyboard's keys. I'm using Arduino+motor shield (legacy Adafruit Motor Shield v1). I've already partially succeeded by using the following code on Matlab:
fig_h = figure;
set(fig_h,'KeyPressFcn', @key_pressed_fcn);
function key_pressed_fcn(fig_obj,eventDat)
a = arduino('COM3')
c = get(fig_obj, 'CurrentKey');
if c == 'e'
motorSpeed(a,2,100);
motorRun(a,2,'forward');
pause(2);
motorSpeed(a,2,0);
end
end
This code runs the motor for a couple of seconds after pressing the 'e' key. The problem is that Matlab connects to Arduino every time the key 'e' is pressed, even though the code runs without interruptions. What I want is for Matlab to connect to Arduino once at the beginning and then run the motor every time the key is pressed without reconnecting again.
If I try to move the line that connects Matlab to Arduino, like this:
a = arduino('COM3')
fig_h = figure;
set(fig_h,'KeyPressFcn', @key_pressed_fcn);
function key_pressed_fcn(fig_obj,eventDat)
c = get(fig_obj, 'CurrentKey');
if c == 'e'
motorSpeed(a,2,100);
motorRun(a,2,'forward');
pause(2);
motorSpeed(a,2,0);
end
end
I think I could avoid needless reconnecting. But running this code results in error message: " Undefined function or variable 'a'.".
Any ideas how to solve this?
  1 Comment
Saurav Shenoy
Saurav Shenoy on 18 Apr 2020
try making it an input to the function but still define it outside the function!

Sign in to comment.

Answers (0)

Communities

More Answers in the  Power Electronics Control

Categories

Find more on Arduino Hardware in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!