t=1:Nf;
camt=((tn-tn(1))*24*3600)*100;

ledt=256-(2.^(0:7)*(ledv>repmat(bb(p),1,Nf)));
a=polyfit(t,camt,6);
ledt1=ledt-ledt(1)+cumsum(256*([0 diff(ledt-polyval(a,t))<-150]));
a1=polyfit(t,ledt1,6);
ledt2=cumsum(128*([0 diff(ledt1-polyval(a1,t))<-100]))+ledt1;
a2=polyfit(t,ledt2,6);
ledt3=cumsum(64*([0 diff(ledt2-polyval(a2,t))<-40]))-cumsum(64*([0 diff(ledt2-polyval(a2,t))>40]))+ledt2;
a3=polyfit(t,ledt3,6);
ledt4=cumsum(32*([0 diff(ledt3-polyval(a3,t))<-22]))-cumsum(32*([0 diff(ledt3-polyval(a3,t))>22]))+ledt3;
a4=polyfit(t,ledt4-camt,6);
ledt5=ledt4-polyval(a4,t);


