Hi,
I'm preparing a project where an ultrasonic sensor changes the rotation speed of the dc motor, depending on the distance.
There are five distances at which the motor should stop rotating, according to the figure we defined in the code language.
For some reason in the measurements I get a correct measurement distance. At a measurement of about 20 cm, the measurement jumps to 1189 cm, and because of this, the engine activity is disrupted.
I would appreciate your assistance.
This is the code:
long duration; // The time it took for the supersonic pulse to return
int distance; // the distance
#define U_trig 8
#define U_echo 9
#define m_1 10
#define m_2 11
#define L_ 28 // Conveyor length
#define loc0 4
#define loc1 11.5
#define loc2 9
#define loc3 6
#define loc4 7
float location[] = {loc0,loc1,loc2,loc3,loc4,}; // The desired distance of the package from the sensor in cm, where I want the motor to stop. There should be five places
void setup()
{
pinMode (U_trig, OUTPUT);
pinMode (U_echo, INPUT);
pinMode (m_1, OUTPUT);
pinMode (m_2, OUTPUT);
Serial.begin(9600);
}
void loop()
{
move(location[20]);
}
void ultrasonic() {
digitalWrite(U_trig, LOW);
delayMicroseconds(2);
digitalWrite(U_trig, HIGH);
delayMicroseconds(10);
digitalWrite(U_trig, LOW);
duration = pulseIn(U_echo, HIGH); // Pulse repetition time in microseconds
distance = duration*0.034 / 2; // distance In cm
Serial.print("distance is: ");
Serial.println(distance);
}
void move (float location)
{
float pre = 0.5; // the degree of accuracy required
int speed;
float delta;
do
}
ultrasonic(); // Current distance check
delta= location-distance;
if (delta<pre)
{
speed=map(delta,pre,L_,30,255);
digitalWrite(m_1, LOW);
analogWrite(m_2, speed);
Serial.println(speed);
delay(1000);;
}
else
{
speed=map((-delta),pre,L_,30,255);
digitalWrite(m_1, HIGH);
analogWrite(m_2, 255-speed);
}
} while (delta > pre || delta < -pre);
}