clear
clc
videoFileReader =imaq.VideoDevice('winvideo',1,'MJPG_640x480');
FaceDetect = vision.CascadeObjectDetector;
EyeDetect = vision.CascadeObjectDetector('EyePairBig');
ss=serial ('COM3','BaudRate',19200,'DataBits',8);
fopen(ss);
while 1
d= step(videoFileReader);
[ns ,ms, vs] =size(d);
b = insertShape(d, 'circle', [ms/2, ns/2, 20],'Color','black');
BB = step(FaceDetect,d);
 if size(BB)==[1,4]
 f=BB(1,1);g=BB(1,2);h=BB(1,3);j=BB(1,4);
p=h/2+f;
o=j/2+g;
u= insertMarker(b, [p o], '+', 'color','red' , 'size', 8);
  figure(1),imshow(u);
rectangle('Position',BB,'LineWidth',2,'LineStyle','-','EdgeColor','r');
 if p<=ms/2-20
fprintf(s,'STEP,0,2');
elseif p>=ms/2+20
  fprintf(s,'STEP,0,1');
 end
if o<= ns/2-20
  fprintf(s,'STEP,1,0');
  elseif o>=ns/2+20
  fprintf(s,'STEP,2,0');
 end
eye=step(EyeDetect,d);
if size(eye)==[1,4] 
 rectangle('Position',eye,'LineWidth',2,'LineStyle','-','EdgeColor','r');
 else
      continue; 
 end
  else
figure(1),imshow(d);
 end

while 1
    if  size(BB)==[0,4]
        break
    end
m=f-40;
n=g-40;
mm=h+40;
nn=j+40;
mk=m+mm;
nk=n+nn;
    if n<=0 || m<=0
        break
      elseif (mk>=ms || nk>=ns)
        break  
    end
 yy= step(videoFileReader);
  [ns ,ms, vs] =size(yy);
    b = insertShape(yy, 'circle', [ms/2, ns/2, 20],'Color','black');
            s=yy(n:nk,m:mk);
  BBc = step(FaceDetect,s);
if size(BBc)==[0,4]
break
end
  if size(BBc)==[1,4]
ff=BBc(1,1);gg=BBc(1,2);hh=BBc(1,3);jj=BBc(1,4);
p=hh/2+ff+m;
o=jj/2+gg+n;
as=m+ff;
bs=n+gg;
u= insertMarker(b, [p o], '+', 'color','red' , 'size', 8);
 figure(1),imshow(u);
rectangle('Position',[as,bs,hh,jj],'LineWidth',2,'LineStyle','-','EdgeColor','r');
if p<=ms/2-20
fprintf(s,'STEP,0,2');
elseif p>=ms/2+20
  fprintf(s,'STEP,0,1');
end
if o<= ns/2-20
  fprintf(s,'STEP,1,0');
  elseif o>=ns/2+20
  fprintf(s,'STEP,2,0');
end
if ms/2-20<p<ms/2+20 && ns/2-20<o<ns/2+20
   fprintf(s,'LASER');
end
eye=step(EyeDetect,s);
if size(eye)==[1,4]
fff=eye(1,1);
ggg=eye(1,2);
hhh=eye(1,3);
jjj=eye(1,4);
lp=fff+m;
lo=ggg+n;
rectangle('Position',[lp,lo,hhh,jjj],'LineWidth',2,'LineStyle','-','EdgeColor','r');
 else
      continue; 
end
   else
   figure(1),imshow(yy);
   end
  
end
end

