I would need some help on my coding.
I am using a maxbotix AE0 ultrasonic sensor with analog output. I need to take the reading from 200cm to 20cm(the minimum).
My main problem is that from very close, the sensor is going crazy and indicating me false readings (works fine if you place your hand very close, but if you wear a glove for exemple, the fabrics of the glove creates unwanted reflections).
Then, i go closer, the output indicates 30... then 25... then it goes 200...900.. 800 and so on...
as soon as I go away from it, it goes back to normal reading.
What I want to do is filter this with the coding. I would like to say something like :
if the precedent reading was 25cm and then it goes straight to 300cm, dont take the last reading and indicate 25cm. But if you go away slowly, then it reads normally. So I just want to filter this unwanted behaviour, not to get some crazy readings when I am too close.
I tried to make this code. And I said, if you are between 25 and 35 cm on the previous reading and then the next one jumps above 100cm, dont take it. It works fine when I go close, but as soon as I am going further away than 100 cm it indicates me 25cm. I dont know where I made the mistake, it looks like it never goes to some of my loops.
Code: Select all
//analog output on pin1
const int Pin_Analog= 1;
//digital pin3 to make the pulse in order to authorize the sensor to range
int Pin_RX= 3;
//anVolt to receive data from analog pin1,
//cm is the most recent range detected,
//previous_cm the precedent range
long anVolt, cm, previous_cm;
void setup() {
previous_cm=0;
Serial.begin(9600);
pinMode(Pin_Analog, INPUT);
}
void loop() {
//pulse to open the range reading
digitalWrite(Pin_Analog, LOW);
delayMicroseconds(50);
digitalWrite(Pin_Analog, HIGH);
delayMicroseconds(50);
digitalWrite(Pin_Analog, LOW);
delayMicroseconds(50);
//read the most recent value on the analog output of the maxsonar
anVolt = analogRead(Pin_Analog);
//convert the reading into cm
cm = (anVolt/2) * 2.54;
//filter, if the previous reading was a close range between 0 to 25 cm and the next reading is something like
//100 (sensor is going crazy), i want it to return cm = 25, otherwise, return the most recent value
if (0 < previous_cm < 35) {
if ( cm > 100) {
cm = 25;
Serial.print(cm);
Serial.print(" cm compensated");
Serial.println();
goto end;
}
else {
Serial.print(cm);
Serial.print(" cm");
Serial.println();
goto end;
}
}
else if (previous_cm >= 35) {
if(cm<200){
Serial.print(cm);
Serial.print(" cm");
goto end;
}
else {
cm=200;
Serial.print(cm);
Serial.print(" cm compensated");
Serial.println();
goto end;
}
}
end:
cmprecedent=cm;
delay(500);
}
33 cm
30 cm
30 cm
35 cm
40 cm
43 cm
38 cm
35 cm
55 cm
55 cm
50 cm
48 cm
40 cm
93 cm
93 cm
99 cm
25 cm compensated
25 cm compensated
25 cm compensated
25 cm compensated
25 cm compensated
25 cm compensated
Does anyone have an idea on whats going wrong ?
Hope someone can help me with this

Jake.