close all; clear all; % close all figure windows and clear workspace

% set up connection to brick
COM_CloseNXT('all');  
hNXT=COM_OpenNXT(); 
COM_SetDefaultNXT(hNXT);

OpenUltrasonic(SENSOR_1); %define sensor on port 1

forward=NXTMotor('BC'); % Define motor command for forward movement
forward.Power=50; 
forward.TachoLimit=0; 

turnRight=NXTMotor('B'); % Define motor command for turning 
turnRight.Power=50;
turnRight.TachoLimit=360; 

for i= 1:5  %do for 5 turns
    while GetUltrasonic(SENSOR_1)>20 
        forward.SendToNXT();
    end %while
    forward.Stop('brake');
    NXT_PlayTone(400,300);
    turnRight.SendToNXT;
    turnRight.WaitFor;
end %for

%cleaning up
turnRight.Stop('off');
forward.Stop('off');
CloseSensor(SENSOR_1);
COM_CloseNXT(hNXT);
close all; clear all;