Hello,
I am trying to write a function to slow a robot down as it approaches a collision. My goal is as the robot approaches an obstruction when it gets 20cm away it starts to slow, and then turns at 10cm. I don't want it to stop so I came up with the slowDown function below. Unfortunately it is not behaving as expected.
The sensor is providing distance readings reliably. When the distance gets below 20cm the runRate jumps to 0.55% of the normal rate. The code is evaluating my math as 0. I've googled this and it seems like it should work. What have I done wrong?
#include <Arduino.h>
#include <NewPing.h>
NewPing sensor(18, 18, 180); // create Ultrasonic sensor class
//Initialize variables
int distance = 50;
#define TOO_CLOSE 10 // Collision detection value
bool speedMode = false; //set max speed for carpet or tile
int tile = 127; // tile max speed
int carpet = 255; // carpet max speed
float runRate = tile; // value to run motor
void setup() {
Serial.begin(57600); //open serial communication
}
void loop() {
delay(50); //allow sensor time to clear
distance = sensor.ping_cm(); // get distance from sensor: returns int
if (distance <= 0) distance = 180; //if no signal set to max
slowDown(distance, speedMode);
move();
}
void slowDown(int distance, bool speedMode) // Adjust motor value as collision approaches
{
if (distance <= (2 * TOO_CLOSE)) {
if (speedMode) {
runRate = (tile * (0.55 + (distance / (2 * TOO_CLOSE)*0.45)));
} else {
runRate = (carpet * (0.55 + (distance / (2 * TOO_CLOSE)*0.45)));
}
} else {
if (speedMode) {
runRate = tile;
} else {
runRate = carpet;
}
}
}
void move() {
Serial.print(distance);
Serial.print(", ");
Serial.println(runRate);
}