Now I created the environment which I need.
Now I need to create the main simulation loop, which I'm struggling. I cannot understand how to implement FLC rules to the matlab code.
% Initialize the environment and figure
figure;
axis([0 120 0 120]); % Define the XY plane size
hold on;
% Define the robot as a small colored solid circle
robot = viscircles([3, 3], 1, 'EdgeColor', 'b', 'LineWidth', 8);
% Manually place obstacles as solid colored squares.
obstacles =[
% Define obstacle coordinates as [x, y, width, height]
rectangle('Position',[50 50 10 10],'EdgeColor','k','FaceColor',[0 .5 .5]);
rectangle('Position',[75 80 20 15],'EdgeColor','k','FaceColor',[0 .5 .5]);
rectangle('Position',[25 15 5 15],'EdgeColor','k','FaceColor',[0 .5 .5]);
];
% Load Fuzzy Logic Controller from a FIS file
flc = readfis('Fuzzy_HW_Sugeno.fis');
% Robot parameters
robotPosition = [3, 3];
goal = viscircles([100, 100], 1, 'EdgeColor', 'y', 'LineWidth', 8);
robotPath = (robotPosition); % Initialize the robot path with the starting position
%{
% Main simulation loop
while norm(robotPosition - goal) > 2 % Adjust the termination condition
% Calculate front, left, and right obstacle distances (you need to implement this)
% For example, you can use sensors or logic to determine obstacle distances
% Use FLC to calculate left and right motor speeds
fuzzyInputs = [Front_OD, Left_OD, Right_OD]; % Replace with actual values
fuzzyOutputs = evalfis(fuzzyInputs, flc);
Left_MS = fuzzyOutputs(1);
Right_MS = fuzzyOutputs(2);
% Update the robot's position based on the motor speeds
delta_speed = Left_MS - Right_MS;
radius = 10;
delta_theta = delta_speed / radius;
robotPosition = robotPosition + [radius * (Right_MS + Left_MS) * cos(delta_theta / 2), ...
radius * (Right_MS + Left_MS) * sin(delta_theta / 2)];
% Check for collisions with obstacles and adjust the robot's trajectory
for i = 1:length(obstacles)
if isCollision(robotPosition, obstacles(i, :))
% Implement collision avoidance logic here
end
end
% Update the plot to reflect the robot's new position and shadow path
set(robot, 'Position', [robotPosition, 2]);
robotPath = [robotPath; robotPosition]; % Append to the robot path
% Plot the robot path
plot(robotPath(:, 1), robotPath(:, 2), 'k.');
pause(0.1); % Adjust the simulation speed
end
% End of the simulation
% Cleanup and visualization
delete(robot);
delete(obstacles);
% Function to check for collision with an obstacle
function collision = isCollision(robotPosition, obstacle)
x = robotPosition(1);
y = robotPosition(2);
obstacle_x = obstacle(1);
obstacle_y = obstacle(2);
width = obstacle(3);
height = obstacle(4);
collision = (x >= obstacle_x && x <= obstacle_x + width && y >= obstacle_y && y <= obstacle_y + height);
end
%}