using servo giving error

2 次查看(过去 30 天)
Md
Md 2022-10-26
Hello, I am using the code below to track red object using servomotor and arduino.
clear all;
a=arduino("/dev/cu.usbmodem101","Uno","Libraries","Servo");
s = servo(a,'D4','MinPulseDuration',5.44e-04,'MaxPulseDuration',2.40e-03);
cam=webcam();
for i = 1:300
RGB = snapshot(cam);
size(RGB)
% defining redness of image
r = RGB(:, :,1); g = RGB(:, : ,2); b = RGB(:, :, 3);
% create a binary image (heuristic)
red = (r > 2*g) & (r > 2*b) & (r > 30);
% imshow(red);
% group all red object within 5 pixels of each other as one object
se = strel('disk',5);
red = imclose(red,se);
% delete all objects smaller than 35 pixels in area
red = bwareaopen(red,35);
red = bwareafilt(red, 1);
% getting the centroid & creating bounding box
stats = regionprops(bwlabel(red),'BoundingBox','centroid');
S = vertcat(stats.Centroid);
figure
imshow(RGB) % show original image
hold on
for object = 1:length(stats)
bb = stats(object).BoundingBox;
bc = stats(object).Centroid;
rectangle('Position', bb, 'EdgeColor', 'r', 'LineWidth', 2) % draw bounding box
plot(bc(1), bc(2), '-m+') % mark centroid (x, y) with '+'
a=text(bc(1)+15,bc(2), strcat('X: ', num2str(round(bc(1))), ' Y: ', num2str(round(bc(2)))));
set(a, 'FontName', 'Arial', 'FontWeight', 'bold', 'FontSize', 12, 'Color', 'yellow');
error = bc(1)-320;
x_dist = error*0.06718;
deg = atan(x_dist/30);
deg_map = (deg+0.6)*(1-0)/(0.6+0.6) + 0;
fprintf('DEG %.2f \n', deg_map)
writePosition(s,deg_map)
end
hold off
end
The issue is, whenever the degree is more than 1, it gives an error saying, "Invalid position value. The value must be between 0 and 1." For example:
What can I do to solve this? Thank you!

回答(1 个)

Amit Dhakite
Amit Dhakite 2023-6-5
Hi Md,
As per my understanding, you are using "writePosition()" in order to track a red object using a servo motor, but encountering an error.
I would like to draw your attention to the fact that the second parameter in the "writePosition()" is the position of servo motor shaft specified as a number representing the angle from 0 to 1, where 0 represents the minimum angle of rotation and 1 represents the maximum angle of rotation of the servo motor. In your code, it looks like this parameter "deg_map" is out of this specified range.
Try to find out the range of "deg". Let's say it is between "deg_min" and "deg_max", then its mapping would be:
deg_map = (deg - deg_min) / (deg_max - deg_min);
This should help bring the "deg_map" parameter within the specified range of 0 and 1.
To know more about “writePosition()”, kindly refer to the following link: https://www.mathworks.com/help/supportpkg/arduinoio/ref/writeposition.html

类别

Help CenterFile Exchange 中查找有关 MATLAB Support Package for Arduino Hardware 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by