Hey Ravyn,
After analysing the code provided by you to control a servo motor using MATLAB code while interfacing with the Arduino Uno, I could see that the code is missing the part where the servo arm needs a command for movement when the button is pressed.
Here is the corrected code snippet:
clear s %clear the servo object if used previously
s = servo(a, 'D9', 'MinPulseDuration', 400*10^-6, 'MaxPulseDuration', 2100*10^-6)
% Define cell array variable for key pins and configure with built-in pullup resistors
keyPins = {'D2','D3'};
configurePin(a,keyPins{1},'pullup');
% Set the position to 0
writePosition(s, 0);
pause(2) % Wait 2 seconds
% While loop runs commands inside as long as the condition in parentheses evaluates to true.
while(1) % Condition in parentheses is always true
% Read states of key pins into vector
keyStates(1) = readDigitalPin(a,keyPins{1});
keyStates(2) = readDigitalPin(a,keyPins{2});
if keyStates(1) == 0 % True if the first key is pressed (pullup resistor makes default state HIGH)
% Move the arm from 0 to 90 degrees
writePosition(s, 0.5); % 0.5 corresponds to 90 degrees if the servo is 0-180 degrees
pause(30); % Wait 30 seconds
% Move the arm back to 0 degrees
writePosition(s, 0);
pause(2); % Small delay to avoid bouncing or multiple reads
end
end
Please note that the “writeposition” function takes a value between 0 and 1, where 0 corresponds to the minimum angle (0 degrees) and 1 corresponds to the maximum angle (typically 180 degrees). So, a value of 0.5 would set the servo to its midpoint, which is typically 90 degrees.
Also, this code assumes that the servo moves linearly across its range, which might not be the case for all servos. You may need to calibrate the position to get exactly 90 degrees if precision is important.
Further to know more about controlling servo motors you can refer to the below MathWorks Documentation:
Hope it helps,
Regards,
Shubham Shreshth