Motor control using keyboard, Matlab and Arduino+shield
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
Saurav Shenoy
le 18 Avr 2020
try making it an input to the function but still define it outside the function!
Réponses (0)
Communautés
Plus de réponses dans Power Electronics Control
Voir également
Catégories
En savoir plus sur Arduino Hardware dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!