Question

I'm reading infrared Sharp distance sensors:

http://www.robofun.ro/senzori/infrarosu/senzor_sharp_%20GP2D120XJ00F

With the reading I'm commanding a servo to direct the robot along a wall, a pretty simple map and write code.

The problem I'm having is that the sensor readings are way off, not behaving liniar... I know other people use these sensors just fine and I know they're wired just fine.

My question is how can I eliminate any oscillations sent to the servo? I'm getting 1 to 3 degrees of oscillations with the robot standing still at a fixed distance from the wall.

Below you have my code:

#include <Servo.h>

Servo myservo;
int val; 
int val1;

int IRpin = A7;
 // analog pin for reading the IR sensor
void setup() {
 myservo.attach(3);

 Serial.begin(9600); // start the serial port
}
void loop() {
 float volts = analogRead(IRpin);

delay(100); 
val1 = map(volts, 230,500, 0 ,100);
 val = map(val1, 0, 100, 100, 80);
 myservo.write(val);
 Serial.println(val);
 }

Please note that double-mapping is necessary because, otherwise variations would be MUCH worse.

Thanks to anyone who will take the time to answer this and help me out...

LE: I've already considered hysteresis, but I want something that will not lose time with unnecessary readings and calculations.

Was it helpful?

Solution

This is a classic control problem. I would recommend looking into PID controllers.

EDIT: sorry, misread the question. I thought you had a desired direction and were using the IR distance sensor to read your current direction. I'll leave the above up as background, but no it doesn't apply to this.

NEW ANSWER:

Sensor fluctuations are completely normal. You have to account for them. In this case I would use a simple moving averages filter. (your distance from the wall at any 1 time is the average of your last X sensor readings). Making x too big will introduce delays, too small and you will have the same noisy output.

In response to your LE note: I don't think you can avoid some form of hysteresis when dealing with noisy inputs. Do you actually have a performance issue yet that you don't want to waste time on calculations? Don't pre-optimize.

EDIT 2: The above will smooth your input signal (current distance). How are you converting this to your output signal (servo setpoint) to achieve your desired distance (assuming you want to stay a fixed distance from a wall)? This is where a PID controller may help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top