Trying to write a unique obstacle avoiding car

I am writing a Arduino script for my Obstacle avoiding Car... It should scan the area for obstacles using both ultrasonics and DHT11 (by calculating speed of sound) to avoid hitting it and go anywhere else, and if there are obstacles everywhere, it should trigger a buzzer with a frequency of 70mHz every 3 seconds for 1 second...

  1. I can't get the motors working
  2. the Ultrasonic seems to be detecting everywhere as obstacle
  3. the Servo rotates 360" not 180" for some reason (which broke my servo. After struggling to move/rotate, the top gear got broken...)
#include <DHT_U.h>
#include <DHT.h>
#include <Servo.h>

#define MOVE_DIRECTION_FORWARD  (0)
#define MOVE_DIRECTION_BACKWARD (1)
#define MOVE_DIRECTION_RIGHT    (2)
#define MOVE_DIRECTION_LEFT     (3)
#define MOVE_DIRECTION_NONE     (4)

Servo zServo;

const int trigPin = 9;
const int echoPin = 10;

const int servoPin = 2;
const int dhtPin = 7;
const int buzzerPin = 8;

const int leftAPin = 3;
const int leftBPin = 4;
const int rightAPin = 5;
const int rightBPin = 6;

DHT_Unified dht(dhtPin, DHT11);

#define SAFE_DIST_CM 3

const int SCAN_ANGLES[] = {0,15,30,45,60,75,90,105,120,135,150,165,180};
const int NUM_SECTORS  = sizeof(SCAN_ANGLES)/sizeof(int);
unsigned long curMovementDirection = MOVE_DIRECTION_NONE;
int distances[NUM_SECTORS];
unsigned long lastBuzzerMillis = 0;
bool buzzerOn = false;
bool commandMode = false;
unsigned long lastScan = 0;

void setup() {
  zServo.attach(servoPin);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  pinMode(leftAPin, OUTPUT);
  pinMode(leftBPin, OUTPUT);
  pinMode(rightAPin, OUTPUT);
  pinMode(rightBPin, OUTPUT);
  
  pinMode(buzzerPin, OUTPUT);
  dht.begin();
  Serial.begin(115200);
  zServo.write(90);
  zServo.writeMicroseconds(1500);
}

int measureDistance(bool unitInch = false, bool enbDHT = false)
{
  float duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = (float)pulseIn(echoPin, HIGH);
  if(enbDHT == false)
      distance = duration * (unitInch ? 0.0133 : 0.034) / 2;
  else
  {
      sensors_event_t DHTsensor[2];
      dht.temperature().getEvent(&DHTsensor[0]);
      dht.humidity().getEvent(&DHTsensor[1]);
      if(isnan(DHTsensor[0].temperature) || isnan(DHTsensor[1].relative_humidity))
      {
          Serial.println("ERROR: reading DHT11 sensor");
          return -1;
      }
      float speedOfSound = 331.4 + (0.6 * DHTsensor[0].temperature) + (0.0124 * DHTsensor[1].relative_humidity);
      duration = duration/1e6f;
      distance = (speedOfSound * duration)/2.0f;
      distance = distance * 100;
      if(unitInch)
          distance = distance/2.54;
  }
  return distance;
}

void MoveForward()
{
  if(curMovementDirection == MOVE_DIRECTION_FORWARD)
    return;
  curMovementDirection = MOVE_DIRECTION_FORWARD;
  digitalWrite(leftAPin, HIGH);
  digitalWrite(leftBPin, LOW);
  digitalWrite(rightAPin, HIGH);
  digitalWrite(rightBPin, LOW);
  Serial.println("DEBUG: Moving forward.");
}

void MoveBackward()
{
  if(curMovementDirection == MOVE_DIRECTION_BACKWARD)
    return;
  curMovementDirection = MOVE_DIRECTION_BACKWARD;
  digitalWrite(leftAPin, LOW);
  digitalWrite(leftBPin, HIGH);
  digitalWrite(rightAPin, LOW);
  digitalWrite(rightBPin, HIGH);
  Serial.println("DEBUG: Moving backward.");
}

void turnInPlace(float angleDeg) {
  bool dirCW = (angleDeg > 0);
  digitalWrite(leftAPin,  dirCW);
  digitalWrite(leftBPin,  !dirCW);
  digitalWrite(rightAPin, !dirCW);
  digitalWrite(rightBPin, dirCW);
  int dur = abs(angleDeg) * 10;
  delay(dur);
  StopMoving();
}

void StopMoving()
{
  if(curMovementDirection == MOVE_DIRECTION_NONE)
    return;
  curMovementDirection = MOVE_DIRECTION_NONE;
  digitalWrite(leftAPin, LOW);
  digitalWrite(leftBPin, LOW);
  digitalWrite(rightAPin, LOW);
  digitalWrite(rightBPin, LOW);
  Serial.println("DEBUG: stopped movement.");
}

void scanEnvironment() {
  for (int i = 0; i < NUM_SECTORS; i++) {
    if(0 <= SCAN_ANGLES[i] <= 180)
    {
      zServo.write(SCAN_ANGLES[i]);
      delay(200);
      distances[i] = measureDistance(false, true);
      char msg[70];
      sprintf(msg, "DEBUG: picked angle %d (sector %d)", distances[i], i);
      Serial.println(msg);
    }
  }
}

int pickBestSector() {
  int bestIdx = -1;
  int maxDist = -1;
  for (int i = 0; i < NUM_SECTORS; i++) {
    if (distances[i] > maxDist) {
      maxDist = distances[i];
      bestIdx = i;
    }
  }
  char msg[70];
  sprintf(msg, "DEBUG: picked best sector %d", bestIdx);
  Serial.println(msg);
  return bestIdx;
}

bool allBlocked() {
  for (int i = 0; i < NUM_SECTORS; i++) {
    if (distances[i] > SAFE_DIST_CM) return false;
  }
  return true;
}

void handleBuzzer() {
  unsigned long now = millis();
  if (buzzerOn) {
    if (now - lastBuzzerMillis >= 1000) {
      noTone(buzzerPin);
      buzzerOn = false;
      lastBuzzerMillis = now;
      Serial.println("DEBUG: Buzzer OFF");
    }
  } else {
    if (now - lastBuzzerMillis >= 3000) {
      tone(buzzerPin, 70);
      buzzerOn = true;
      lastBuzzerMillis = now;
      Serial.println("DEBUG: Buzzer ON");
    }
  }
}

void loop() {
  if (millis() - lastScan > 500) {
    scanEnvironment();
    lastScan = millis();
  }

  if (allBlocked()) {
    Serial.println("DEBUG: All sectors blocked!");
    curMovementDirection = MOVE_DIRECTION_BACKWARD;
    MoveBackward();
    delay(500);
    StopMoving();

    commandMode = true;
    lastBuzzerMillis = millis();
    buzzerOn = false;
    return;
  }
  if (commandMode) {
    handleBuzzer();
    return;
  }

  int bestIdx = pickBestSector();
  if(bestIdx != -1)
  {
    int sectorAngle = SCAN_ANGLES[bestIdx];
    float bestAngle = sectorAngle - 90.0;

    if (bestAngle < 0) {
      if(curMovementDirection == MOVE_DIRECTION_LEFT)
        return;
      curMovementDirection = MOVE_DIRECTION_LEFT;
      turnInPlace(bestAngle);
      Serial.println("DEBUG: Moving Left.");
      return;
    } else if (bestAngle > 0) {
      if(curMovementDirection == MOVE_DIRECTION_RIGHT)
        return;
      curMovementDirection = MOVE_DIRECTION_RIGHT;
      Serial.println("DEBUG: Moving Right.");
      turnInPlace(bestAngle);
      return;
    } else {
      curMovementDirection = MOVE_DIRECTION_FORWARD;
      MoveForward();
      return;
    }
  }
  Serial.println("DEBUG: No best sector found (this should ideally not happen).");
  delay(400);
  StopMoving();
}

Then it is not a servo. Sometimes these are called continuous rotational servos, but they can not be set to a position only a speed of rotation.

That physical layout diagram is a bit useless as it doesn't show where to power is coming from to drive the motors from the long obsolete L296. And the bunch of blue wires coming from the L296 board, converging into a single point, and then going to some pins on what I presume is an rip off Arduino Nano clone, is a new low in clarity.

meagHz? even 70kHz is above the hearing range of most humans (~20kHz)

is the an enable pin that either needs to be jumpered on the motor board or diven with a PWM output

you may need to wait for the aoustic wave to dissipate between measurements, otherwize it detects the echo(s) from the previous pings

obviously you need to replace the servo (or just the gear).

but in general you should individually test each of these components and gaining an understanding, integrate them together

you seemed to have written a lot of code (or downloaded it). a common practice is to start simple, test each new feature and add features one at a time. Start with moving at a slow speed using a PWM signal to drive the Enable pin

the algorith for your robot is not obvious from looking at the code. why is StopMiving() called at the end of loop()?

i don't understand the notion of allBlocked(). Surely the robot can be turned 180deg and continue to move

another thing to bear in mind is that by detecting an object from farther away may only require a relatively minor (e.g. 15 deg) direction change to avoid

also, each function should have a well defined purpose. i don't understand why your measureDistance() is doing anything other than return the distance. why is it looking at temperature/humidity, that should be a separate function

measureDistance() is doing anything other than return the distance. why is it looking at temperature/humidity, that should be a separate function

I got the idea of Humidity&temp from Ultrasonic Sensor HC-SR04 and Arduino - Complete Guide which makes sense (at least for me) it is measuring distance between the car and the obstacle using both Ultrasonic and humidity sensors...

i don't understand the notion of allBlocked(). Surely the robot can be turned 180deg and continue to move

It returns a boolean when there is any obstacle detected...

is the an enable pin that either needs to be jumpered on the motor board or diven with a PWM output

It is already enabled with a jumper

meagHz? even 70kHz is above the hearing range of most humans (~20kHz)

sorry I mistyped this part... but it seems to be very high during testing

but in general you should individually test each of these components and gaining an understanding, integrate them together

I will take that into action

Then it is not a servo. Sometimes these are called continuous rotational servos, but they can not be set to a position only a speed of rotation.

it is a FS90 Servo but it seems to be broken...

That physical layout diagram is a bit useless as it doesn't show where to power is coming from to drive the motors from the long obsolete L296.

i will try recreating that diagram

That does not mean that it is not a continuous rotation "servo"

you might find this useful
(working with a robotics student where we can use this

#include <Servo.h>

Servo servo;

const int PinTrig   =  9;
const int PinEcho   = 10;

const int PinServo  =  2;
const int PinDht    =  7;
const int PinBuzzer =  8;

const int PinIn1    =  3;
const int PinIn2    =  4;
const int PinIn3    =  5;
const int PinIn4    =  6;
const int PinEnA    =  7;
const int PinEnB    =  8;


// -----------------------------------------------------------------------------
const int SpdNorm = 150;
const int SpdSlow = 100;

void setSpeed (
    int  spdLeft,
    int  spdRight )
{
    int dir = 0 < spdLeft;
    digitalWrite (PinIn1,   dir);
    digitalWrite (PinIn2, ! dir);
    analogWrite  (PinEnA, abs (spdLeft));

    dir = 0 < spdRight;
    digitalWrite (PinIn3, ! dir);
    digitalWrite (PinIn4,   dir);
    analogWrite  (PinEnA, abs (spdRight));
}

// -----------------------------------------------------------------------------
float
getDistanceIn ()
{
    digitalWrite      (PinTrig, HIGH);
    delayMicroseconds (10);
    digitalWrite      (PinTrig, LOW);

    return pulseIn (PinEcho, HIGH) * 0.0133 / 2;
}

// ---------------------------------------------------------
const int   ScanAng0    = 0;
const int   ScanAngN    = 180;
const int   ScanAng     = 10;

const int   NscanPos    = (ScanAngN - ScanAng0) / ScanAng;
const int   ScanPosMid  = 1 + NscanPos / 2;

      int   scanDir   = 1;
      int   scanIdx;
      float scanDist [NscanPos];

// -------------------------------------
void scanUpdt ()  {
    scanDist [scanIdx] = getDistanceIn ();

    if (scanIdx <= 0 || NscanPos <= scanIdx)
        scanDir = -scanDir;         // reverse direction
    scanIdx += scanDir;

    servo.write (scanIdx * ScanAng);
}

// -------------------------------------
const float DistSafeIn = 20;

int scanDistMax;
int scanDistMin;
int scanDistAng;

void scanAnalysis ()
{
    scanDistMax = 0;
    scanDistMin = 100;
    for (int n = 0; n < NscanPos; n++)  {
        if (scanDistMin > scanDist [n])  {
            scanDistMin  = scanDist [n];
            scanDistAng = (n - ScanPosMid) * ScanAng;
        }
        else if (scanDistMax < scanDist [n])
            scanDistMax = scanDist [n];
    }

    // simplest to just look at side
    //    could also account for distance and angle
    //    turn harder when distance closer and angle smaller
    if (DistSafeIn > scanDistMin)  {
        if (0 < scanDistAng)                // to the right
            setSpeed (SpdSlow, SpdNorm);
        else                                // center or to left
            setSpeed (SpdNorm, SpdSlow);
    }
    else
        setSpeed (SpdNorm, SpdNorm);
}

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
const unsigned long MsecScan = 50;      // 25 ft at 1 ft/msec
      unsigned long msec0;

void loop ()
{
    unsigned long msec = millis ();

    if (msec - msec0 >= MsecScan)  {
        msec0 += MsecScan;

        scanAnalysis ();
    }
}


// -----------------------------------------------------------------------------
void setup ()
{
    Serial.begin (115200);

    pinMode (PinEcho, INPUT);
    pinMode (PinTrig, OUTPUT);
    digitalWrite (PinTrig, LOW);

    pinMode (PinIn1,  OUTPUT);
    pinMode (PinIn2,  OUTPUT);
    pinMode (PinIn3,  OUTPUT);
    pinMode (PinIn4,  OUTPUT);


    servo.attach (PinServo);
}

Speed of sound is an estimate. Temperature, barometric pressure and humidity have an effect whose data can be included in the "more accurate" speed of sound estimation.

Use 880Hz. Annoying enough to get your attention.

You will need to use the circumference of your wheel to determine how far each wheel will travel with each revolution to be used in calculating what a turn needs (inside wheel stopped, outside wheel travels "x.y" rotations to travel "pi/2" radians (90 degree turn).

You will have choices on steering methods. (1) Basic (forward, backward, rotate left, rotate right), (2) Skid (one motor is stopped, the other motor drives (forward skid left, forward skid right, backward skid left, backward skid right), (3) PWM steering - not freewheeling, but proportional driving wheels with PWM to slightly increase or decrease the wheel's speed to make the desired turn.

It is fun-time with math. Enjoy.

i think something is wrong with my Hardware Installation... it is still not moving (the DC Motors)

#include <DHT_U.h>
#include <DHT.h>
#include <Servo.h>

#define MOVE_DIRECTION_FORWARD  (0)
#define MOVE_DIRECTION_BACKWARD (1)
#define MOVE_DIRECTION_RIGHT    (2)
#define MOVE_DIRECTION_LEFT     (3)
#define MOVE_DIRECTION_NONE     (4)

const int SpdNorm = 150;
const int SpdSlow = 100;
const int SpdFast = 200;
const int SpdMax  = 255;

Servo zServo;

const int trigPin = 9;
const int echoPin = 10;

const int servoPin = 2;
const int dhtPin = 7;
const int buzzerPin = 8;

const int leftAPin = 3;
const int leftBPin = 4;
const int leftSpPin = 11;
const int rightAPin = 5;
const int rightBPin = 6;
const int rightSpPin = 12;

DHT_Unified dht(dhtPin, DHT11);

#define SAFE_DIST_CM 3

unsigned long curMovementDirection = MOVE_DIRECTION_NONE;
const int SCAN_ANGLES[] = {0,15,30,45,60,75,90,105,120,135,150,165,180};
const int NUM_SECTORS  = sizeof(SCAN_ANGLES)/sizeof(int);
int scanIdx = 0;
int scanDir = +1;
float distances[NUM_SECTORS];
unsigned long lastBuzzerMillis = 0;
bool buzzerOn = false;
bool commandMode = false;
unsigned long lastScan = 0;

void setup() {
  zServo.attach(servoPin);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  pinMode(leftAPin, OUTPUT);
  pinMode(leftBPin, OUTPUT);
  pinMode(leftSpPin, OUTPUT);
  pinMode(rightAPin, OUTPUT);
  pinMode(rightBPin, OUTPUT);
  pinMode(rightSpPin, OUTPUT);
  
  pinMode(buzzerPin, OUTPUT);
  dht.begin();
  Serial.begin(115200);
  zServo.write(90);
  zServo.writeMicroseconds(1500);
}

int measureDistance(bool unitInch = false, bool enbDHT = false)
{
  float duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = (float)pulseIn(echoPin, HIGH);
  if(enbDHT == false)
      distance = duration * (unitInch ? 0.0133 : 0.034) / 2;
  else
  {
      sensors_event_t DHTsensor[2];
      dht.temperature().getEvent(&DHTsensor[0]);
      dht.humidity().getEvent(&DHTsensor[1]);
      if(isnan(DHTsensor[0].temperature) || isnan(DHTsensor[1].relative_humidity))
      {
          Serial.println("ERROR: reading DHT11 sensor");
          return -1;
      }
      float speedOfSound = 331.4 + (0.6 * DHTsensor[0].temperature) + (0.0124 * DHTsensor[1].relative_humidity);
      duration = duration/1e6f;
      distance = (speedOfSound * duration)/2.0f;
      distance = distance * 100.0f;
      if(unitInch)
          distance = distance/2.54f;
  }
  return distance;
}

void calculateSpeed(int angleErr, int distErr, int &vL, int &vR) {
  const float Kp_ang  = 1.0f;
  const float Kp_dist = 2.0f;
  int delta = (int)(Kp_ang*angleErr + Kp_dist*(SAFE_DIST_CM - distErr));
  int baseSpeed = SpdNorm;
  vL = constrain(baseSpeed + delta, -255, +255);
  vR = constrain(baseSpeed - delta, -255, +255);
}

void MoveForward(int spdLeft, int spdRight)
{
  if(curMovementDirection == MOVE_DIRECTION_FORWARD)
    return;
  curMovementDirection = MOVE_DIRECTION_FORWARD;
  digitalWrite(leftAPin, HIGH);
  digitalWrite(leftBPin, LOW);
  analogWrite(leftSpPin, abs(spdLeft));
  digitalWrite(rightAPin, HIGH);
  digitalWrite(rightBPin, LOW);
  analogWrite(rightSpPin, abs(spdRight));
  Serial.println("DEBUG: Moving forward.");
}

void MoveBackward(int spdLeft, int spdRight)
{
  if(curMovementDirection == MOVE_DIRECTION_BACKWARD)
    return;
  curMovementDirection = MOVE_DIRECTION_BACKWARD;
  digitalWrite(leftAPin, LOW);
  digitalWrite(leftBPin, HIGH);
  analogWrite(leftSpPin, abs(spdLeft));
  digitalWrite(rightAPin, LOW);
  digitalWrite(rightBPin, HIGH);
  analogWrite(rightSpPin, abs(spdRight));
  Serial.println("DEBUG: Moving backward.");
}

void turnInPlace(float angleDeg, int spdLeft, int spdRight) {
  bool dirCW = (angleDeg > 0);
  digitalWrite(leftAPin,  dirCW);
  digitalWrite(leftBPin,  !dirCW);
  analogWrite(leftSpPin, abs(spdLeft));
  digitalWrite(rightAPin, !dirCW);
  digitalWrite(rightBPin, dirCW);
  analogWrite(rightSpPin, abs(spdRight));
  char txt[50];
  sprintf(txt, sizeof(txt), "DEBUG: Moving towards angle %f\".", angleDeg);
  Serial.println(txt);
}

void StopMoving()
{
  if(curMovementDirection == MOVE_DIRECTION_NONE)
    return;
  curMovementDirection = MOVE_DIRECTION_NONE;
  digitalWrite(leftAPin, LOW);
  digitalWrite(leftBPin, LOW);
  analogWrite(leftSpPin, 0);
  digitalWrite(rightAPin, LOW);
  digitalWrite(rightBPin, LOW);
  analogWrite(rightSpPin, 0);
  Serial.println("DEBUG: stopped movement.");
}

void scanEnvironment() {
  zServo.write(SCAN_ANGLES[scanIdx]);
  delay(50);

  distances[scanIdx] = measureDistance(false, true);
  char msg[70];
  sprintf(msg, sizeof(msg), "DEBUG: picked angle %d (sector %d)", distances[scanIdx], scanIdx);
  Serial.println(msg);

  if (scanIdx == 0 || scanIdx == NUM_SECTORS
  -1) scanDir = -scanDir;
  scanIdx += scanDir;
}

int pickBestSector() {
  int bestIdx = -1;
  int maxDist = -1;
  for (int i = 0; i < NUM_SECTORS; i++) {
    if (distances[i] > maxDist) {
      maxDist = distances[i];
      bestIdx = i;
    }
  }
  char msg[70];
  sprintf(msg, sizeof(msg), "DEBUG: picked best sector %d", bestIdx);
  Serial.println(msg);
  return bestIdx;
}

bool allBlocked() {
  for (int i = 0; i < NUM_SECTORS; i++) {
    if (distances[i] > SAFE_DIST_CM) return false;
  }
  return true;
}

void handleBuzzer() {
  unsigned long now = millis();
  if (buzzerOn) {
    if (now - lastBuzzerMillis >= 1000) {
      noTone(buzzerPin);
      buzzerOn = false;
      lastBuzzerMillis = now;
      Serial.println("DEBUG: Buzzer OFF");
    }
  } else {
    if (now - lastBuzzerMillis >= 3000) {
      tone(buzzerPin, 70);
      buzzerOn = true;
      lastBuzzerMillis = now;
      Serial.println("DEBUG: Buzzer ON");
    }
  }
}

int lastIdx = -1;
void loop() {
  if (millis() - lastScan > 500) {
    scanEnvironment();
    lastScan = millis();
  }

  if (allBlocked()) {
    Serial.println("DEBUG: All sectors blocked!");
    curMovementDirection = MOVE_DIRECTION_BACKWARD;
    MoveBackward(SpdSlow, SpdSlow);
    delay(500);
    StopMoving();

    commandMode = true;
    lastBuzzerMillis = millis();
    buzzerOn = false;
    return;
  }
  if (commandMode) {
    handleBuzzer();
    return;
  }

  if (scanIdx == lastIdx) {
    int bestIdx = pickBestSector();
    if(bestIdx != -1)
    {
      float dMin = 999;
      int idxMin = 0;
      for (int i = 0; i < NUM_SECTORS; i++) {
        if (distances[i] < dMin) {
          dMin   = distances[i];
          idxMin = i;
        }
      }
      int angleErr = SCAN_ANGLES[idxMin] - 90;
      int distErr  = (int)dMin;
      int carSpeed[2];
      calculateSpeed(angleErr, distErr, carSpeed[0], carSpeed[1]);

      int sectorAngle = SCAN_ANGLES[bestIdx];
      float bestAngle = sectorAngle - 90.0;

      if (bestAngle < 0) {
        if(curMovementDirection == MOVE_DIRECTION_LEFT)
          return;
        curMovementDirection = MOVE_DIRECTION_LEFT;
        turnInPlace(bestAngle, carSpeed[0], carSpeed[1]);
        Serial.println("DEBUG: Moving Left.");
        return;
      } else if (bestAngle > 0) {
        if(curMovementDirection == MOVE_DIRECTION_RIGHT)
          return;
        curMovementDirection = MOVE_DIRECTION_RIGHT;
        Serial.println("DEBUG: Moving Right.");
        turnInPlace(bestAngle, carSpeed[0], carSpeed[1]);
        return;
      } else {
        curMovementDirection = MOVE_DIRECTION_FORWARD;
        MoveForward(carSpeed[0], carSpeed[1]);
        return;
      }
    }
    Serial.println("DEBUG: No best sector found (this should ideally not happen).");
    delay(400);
    StopMoving();

    lastIdx = scanIdx;
  }
}

The debug statements state "stop movement" even at 400cm, so the logic in the code is told to stop the motors.

Why this:

  char txt[50];
  sprintf(txt, sizeof(txt), "DEBUG: Moving towards angle %f\".", angleDeg);
  Serial.println(txt);

Rather than this:

  Serial.print("DEBUG: Moving towards angle ");
  Serial.println(angleDeg);

I see the right motor being commanded to move.
I never see the left motor being commanded at any distance.
Your index gets out of control, referencing negative elements of the array, which causes memory issues. The presence of setting something to "-1" is another indication of losing control of the index value.

Just use int scanDir = 1;

try a simple program to enable the motors

do you have the jumpers on the ENA and ENB pins

image

consider adding something like the following (some what edited to exercise the different parts of your code. Add an autoFlag to en/disable your existing code

do you have the jumpers on the ENA and ENB pins

no i removed them in order to use the pins for speed control

Your index gets out of control, referencing negative elements of the array, which causes memory issues. The presence of setting something to "-1" is another indication of losing control of the index value.

thanks for pointing out this mistake

I never see the left motor being commanded at any distance.

i thought that it is commanded in MoveLeft function(turnInPlace) using digitalWrite... i have to rewrite this part again

which arduino pins did you connect to them? and where in your code do you control the speed?

which arduino pins did you connect to them?

Pins 11 and 12 (this one specifically seems to be wrong because of PWM)

where in your code do you control the speed?

isn't this from the code i suggested in port #8?

I never see the code call MoveLeft() with the distance from 2 to 400.

1 Like

There is still no update of your schematic. It seems your capacitor is connected reversed...
The white side should have minus marks and should be connected to gnd...
If you keep using fritzy:
Use black for gnd, red for 5V.
Different colors for signals...
Place the components in such a way that you minimize the wire crossings.

1 Like