code in Arduino:
double IR;
void setup() {
Serial.begin(9600);
delay(100);
}
void loop() {
IR1 = read_gp2d12_range(1);
Serial.println(IR);
IR2 = read_gp2d12_range(2);
Serial.println(IR2);
if (Serial.read()==1)
digitalWrite(1, HIGH);
else if (Serial.read()==0)
digitalWrite(1, LOW);
delay(1000);
}
float read_gp2d12_range(byte pin) {
int tmp;
double value;
tmp = analogRead(pin);
value=(6787.0 /((float)tmp - 3.0)) - 4.0;
if (tmp < 4) return 0;
else if (value < 4.0 || value >90.0) return 0.0;
return value;
}
Code in MATLAB:
s= serial('COM3', 'BaudRate', 9600, 'Parity', 'none', 'DataBits', 8);
fopen(s)
z=fscanf(s);
[s1 s2] = size(z);
x = (1:2160)';
s3=2160;
title('Incomming Data from Arduino');
xlabel('Time');
ylabel('cm');
i=0;
i=i+1;
if s1>=2160;
y=zeros(s3,s2);
y(:,1)=z(1+i:2160+i,1);
y(:,2)=z(1+i:2160+i,2);
fitlin = 'F_linear(x, a,b)';
fitfunc='(c-d)*F_sigmoid(x, a, b)+d';
initval= [0 10 50 0 ]
L1max=max(z,1+i:2160+i,1);
L1min=min(z,1+i:2160+i,1);
L2max=max(z,1+i:2160+i,2);
L2min=min(z,1+i:2160+i,2);
L1=L1max-L1min;
L2=L2max-L2min;
[fity1] = fit(x, y(:,1), fittype(fitfunc),...
fitoptions('Method','NonLinear','Start',initval));
[fity1_1]= fit(x, y(:,1), fittype(fitlin),...
fitoptions('Method','NonLinear','Start',[Lmax Lmin]));
plot(fity1, x, y(:,1),'b.'); hold on;
plot(fity1_1);hold on;
g1=fity1.a;
plot(g1, fity1(g1),'k*');hold on;
[fity2] = fit(x, y(:,2), fittype(fitfunc),...
fitoptions('Method','NonLinear','Start',initval));
[fity2_1]= fit(x, y(:,2), fittype(fitlin),...
fitoptions('Method','NonLinear','Start',[Vmax Vmin]));
plot(fity2, x, y(:,2),'b.'); hold on;
plot(fity2_1);hold on;
g2=fity2.a;
plot(g2, fity2(g2),'k*');hold on;
if (fity1.a<2160 && fity1_1.a<-1)
fprintf(s, '1');
end
if (fity2.a>0 && fity2.a<2160 && fity2_1.a>0.3)
fprintf(s, '0');
end
I use Arduino to read data 10(s) once, and do curvefitting in matlab 6(hr) (It's a slide window). write a value back to arduino and trigger motor.