Use MATLAB and the Arduino UNO Board to simulate the operati
Solution
function traffic ( cycle_num )
cars = 0;
cars_in = 0;
cars_out = 0;
car_wait_cycles = 0;
cycle = 0;
cycle_length = 10;
green_cycles = 2;
green_timer = 0;
light = \'r\';
p = 0.3;
red_cycles = 4;
red_timer = 0;
% plotting data
plot_data = zeros(2,cycle_num+1);
% handling first cycle
plot_data(1,cycle+1) = cycle;
plot_data(2,cycle+1) = cars;
prq ( cars, light, cycle );
for cycle = 1 : cycle_num
r = rand ( cycle_length, 1 );
cars_new = sum ( r < p );
cars = cars + cars_new;
cars_in = cars_in + cars_new;
% Handle this time cycle depending on whether the light is green or red.
if ( light == \'g\' )
[ cars, cars_out, light, green_timer ] = go ( green_cycles, cars, ...
cars_out, light, green_timer );
else
[ cars, light, red_timer ] = stop ( red_cycles, cars, light, red_timer );
end
% calculating how many are waiting
car_wait_cycles = car_wait_cycles + cars;
prq ( cars, light, cycle );
plot_data(1,cycle+1) = cycle;
plot_data(2,cycle+1) = cars;
end
plot ( plot_data(1,1:cycle_num+1), plot_data(2,1:cycle_num+1) )
xlabel ( \'Time Cycles\' )
ylabel ( \'Cars Waiting\' )
title ( \'Traffic waiting at a Light\' )
fprintf ( 1, \'\ \' );
fprintf ( 1, \' Number of cycles = %d\ \', cycle_num );
fprintf ( 1, \' Simulated time = %d seconds\ \', cycle_num * cycle_length );
fprintf ( 1, \' Number of cars in = %d\ \', cars_in );
fprintf ( 1, \' Number of cars waiting = %d\ \', cars );
fprintf ( 1, \' Number of cars out = %d\ \', cars_out );
fprintf ( 1, \' Percentage Out/In = %7.1f%%\ \', 100 * cars_out / cars_in );
wait_average_seconds = car_wait_cycles * cycle_length / cars_in;
fprintf ( 1, \' Average wait = %7.2f seconds\ \', wait_average_seconds );
wait_average_lights = car_wait_cycles / cars_in / ( red_cycles + green_cycles );
fprintf ( 1, \' Average wait = %7.2f light cycles\ \', wait_average_lights );
return
end
function [ cars, cars_out, light, green_timer ] = go ( green_cycles, cars, ...
cars_out, light, green_timer )
cars_through = min ( 8, cars );
cars = cars - cars_through;
cars_out = cars_out + cars_through;
green_timer = green_timer + 1;
if ( green_cycles <= green_timer )
light = \'r\';
green_timer = 0;
end
return
end
function [ cars, light, red_timer ] = stop ( red_cycles, cars, light,red_timer )
red_timer = red_timer + 1;
if ( red_cycles <= red_timer )
light = \'g\';
red_timer = 0;
end
return
end
function prq ( cars, light, cycle )
fprintf ( 1, \'%4d \', cycle );
if ( light == \'r\' )
fprintf ( \'R \' );
else
fprintf ( \'G \' );
end
i = cars;
c = floor ( i / 100 );
i = i - 100 * c;
for j = 1 : c
fprintf ( \'C\' );
end
x = floor ( i / 10 );
i = i - 10 * x;
for j = 1 : x
fprintf ( \'X\' );
end
for j = 1 : i
fprintf ( \'I\' );
end
fprintf ( 1, \'\ \' );
return
end

