I need your help in checking my code.Urgent please.

The thing is that I wrote a big code for a robot that has to go through a maze(need for a contest)BUT when I loaded this code into the robot,it just did not move,but stood still and just endlessly measured with an ultrasonic sensor…I can’t find my bug in the code,and I’m pretty sure the bug is in the code, not in the robot.So I ask you to check my code and tell me what the error is.
And so the components of my robot: 1 ultrasonic sensor located on the servo, the wheels on the 2 motors (rear),and the front of the robot conventional rotary wheel without control.All this is located on a small platform,here is the Arduino UNO Board,which controls the sensor,servo and electric motors.
I wrote explanations(comments) in the code in my native language…

ROBOT_3_eng.ino (4.33 KB)

What do I need to do to view your code?

In the sense of?In order to read my code?, Just download it)

Antony289:
The thing is that I wrote a big code for a robot

I presume you wrote lots of little programs to test all the parts before you combined them into the "big code"

If not then you have a lot of work ahead of you and writing "URGENT" in your title is not going to help.

If you did develop the program in stages then post the latest version that worked and tell what changes you have subsequently made that have caused it to stop working.

It would also be a big help if you could translate your comments to English.

And I notice that you have a lot of lines such as

analogWrite(3,shim1);

which use the pin number. It is much easier to understand code if you give names to the pin numbers as in

digitalWrite(trigPin, HIGH);

To make it easier to read your code please use the AutoFormat tool to indent it consistently.

...R

The fact that I wrote this code in stages, in parts, and I wrote "Urgent" because of the fact that this contest is soon (passing the labyrinth robot).
But I loaded into the robot immediately all the code received (I realized that this was an error , that it is necessary to load the code into the robot in stages and check ... it will be for me a lesson)
I do not know whether I will have time to translate all the comments into English, because now I have a very strong load and almost no time.
And about the replacement of pin numbers in the words-thank you, I forgot about this)
Can you please clarify my mistakes in the code?

/////////////////№2
////////////////СТОРОНЫ/////////////
int right; //правая сторона
int left;  //левая сторона
int line; //прямо сторона
int maxRight ; //максимальная(бОльшая) правая сторона
int maxLeft; //максимальная(бОльшая) левая сторона
////////////////////////////////////

///////////////НАСТРОЙКИ!!////////////////////  ///  ///  ///  ///  ///  ///  ///  ///  ///
int sec = 3000 ; // найти опытным путём проезд робота за один/два блока лабиринта         ///
////////////////////////////////////////////  ///  ///  ///  ///  ///  ///  ///  ///  ///
#include <Servo.h> //ввод библиотеки сервопривода
float distance;
int min_distance = 30;
int duration, cm ;
int max ;
int MAX; //вводим переменную "МАксимальная сторона"
Servo servo1 ;
#define echoPin 7
#define trigPin 8
int duration1;
int duration2;
int duration3;
unsigned long timeNOWLine;
unsigned long timeLINE;
int timing ;
int shim1 ;
int shim2 ;
int shim3;
int shim4;
void setup()  /////////////    ///////////      //////////////    //////////       //////////     /////////     ////////     //////////       //////////     ////// НАЧАЛО
{ servo1.attach(3); ///сервопривод
  pinMode(6, OUTPUT); //левый двигатель назад
  pinMode(3, OUTPUT); //левый двигатель вперёд
  pinMode(5, OUTPUT); //правый двигатель назад
  pinMode(11, OUTPUT); //правый двигатель вперёд
  pinMode(3, OUTPUT); //сервопривод
  pinMode(trigPin, OUTPUT); //триг датчик
  pinMode(echoPin, INPUT); //ечхо датчик
}

void loop() {
  shim1 = 77; //////////////////////////////////// ШИМ
  shim2 = 80;
  shim3 = 82; // сверить
  shim4 = 84; //сверить
  analogWrite(3, shim1);
  analogWrite(11, shim2);
  analogWrite(5, shim3);
  analogWrite(6, shim4);
  servo1.write(0) ;///////////////////////////////////////////////////////////начало замерения(1-ая замерка)ПРАВАЯ СТОРОНА
  delay (500) ;
  digitalWrite(trigPin, LOW); //
  delayMicroseconds(2);//
  digitalWrite(trigPin, HIGH); //
  delayMicroseconds(10);//
  digitalWrite(trigPin, LOW); //
  duration1 = pulseIn(echoPin, HIGH); //первый замер ультразвукового датчика
  right = duration1 / 58; //
  Serial.print(cm);//
  Serial.println("cm");//
  delay(100);//

  servo1.write(90) ;///////////////////////////поворот сервопривода 90 градусов
  delay(500) ;

  digitalWrite(trigPin, LOW); ////////////////////////////////////2-ая ЗАМЕРКА ПРЯМО
  delayMicroseconds(2);///
  digitalWrite(trigPin, HIGH); ///
  delayMicroseconds(10);///
  digitalWrite(trigPin, LOW); ///
  duration2 = pulseIn(echoPin, HIGH); ///второй замер ультразвукового датчика
  line = duration2 / 58; ///
  Serial.print(cm);///
  Serial.println("cm");///
  delay(100);///

  servo1.write(180) ;////////////// поворот сервопривода на 180 градусов
  delay(500) ;

  digitalWrite(trigPin, LOW); /////////////////////////////////////////3-я ЗАМЕРКА ВЛЕВО
  delayMicroseconds(2);////
  digitalWrite(trigPin, HIGH); ////
  delayMicroseconds(10);////
  digitalWrite(trigPin, LOW); ////
  duration3 = pulseIn(echoPin, HIGH); ////третий замер ультразвукового датчика
  left = duration3 / 58; ////
  Serial.print(cm);////
  Serial.println("cm");////
  delay(100);////

  if ((duration1 + duration2 + duration3) <= 36) //если сумма длин сторон меньше или равна 36 сантиметрам,то едим назад
  { //БЛОК ТУПИКА
    analogWrite(5, HIGH); //едим назад
    analogWrite(6, HIGH);
    delay(1500);   //сверить
    analogWrite(5, LOW);
    analogWrite(6, LOW);
  }

  if (right > left) //если правая сторона больше левой
  { MAX = right;
  }
  else // в противном случае
  { MAX = left;
  }

  if (MAX < LINE) //если максимальная сторона меньше чем сторона прямо,то исп блок прямо
  {
    LINE();
  }
  else
  {
    if (right > left)
    {
      RIGHT();
    }
    else {
      LEFT();
    }
  }
  ///////////////////////////////////////////////////////////////здесь сравнение писать!между правой и левой стороной

  //  if (maxRight > line)
  //   {
  //   RIGHT();
  //   }
  //  else LINE(); ///если прямо больше чем право
  //
  //  else LEFT();


}/////////КОНЕЦ

void LINE()                            ////////////////////////////////блок для езды ВПЕРЁД
{
  if (distance > min_distance)//если расстояние впереди больше заданного
  {
    analogWrite(3, shim1); //едим вперёд
    analogWrite(11, shim2);
    delay(650);
  }
  else
  { analogWrite(3, LOW); //не едим
    analogWrite(11, LOW);
  }
}

void RIGHT()                          ///////////////////////////////////// блок для поворота НАПРАВО
{ analogWrite(3, HIGH);
  delay(260);//задержка
  analogWrite(3, LOW);
}

void LEFT() {                 //////////////блок для поворота на ЛЕВО
  digitalWrite(11, HIGH); ///правое колесо вперёд
  delay(220); //задержка
  digitalWrite(11, LOW);
}

I’m guessing Russian.
The forum has a Russian section

Antony289:
now I have a very strong load and almost no time.

Lack of time is not any of our concern.

You should have planned according.

.

Antony289:
Can you please clarify my mistakes in the code?

I can't because I can't make sense of it as I don't know Russian and you have not got meaningful names for pins that might help me.

...R

void RIGHT() 
{ 
  analogWrite(3, HIGH);
  delay(260);
  analogWrite(3, LOW);
}

void LEFT() 
{
  digitalWrite(11, HIGH);
  delay(220);
  digitalWrite(11, LOW);
}

analogWrite (3, HIGH) is a very, very low duty cycle.

Look at the differences between LEFT and RIGHT

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH); 
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW); 
  duration1 = pulseIn(echoPin, HIGH);

This is crazy.
If you had initialised trigPin to LOW in setup(), then this code would simply be

  digitalWrite(trigPin, HIGH); 
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW); 
  duration1 = pulseIn(echoPin, HIGH);

This repeated sequence should also be in a function, returning a range in centimetres.

  if ((duration1 + duration2 + duration3) <= 36)

My Russian isn’t what it was, but I’m guessing that that line should read

  if ((left + line + right) <= 36)
 servo1.attach(3);
 ...
  pinMode(3, OUTPUT);
 ...
    analogWrite(3, shim1);

I see that as being a problem.

Antony289:
In the sense of?In order to read my code?, Just download it)

No. I also have to open it with a proper app. Or at least change the extension from ino to txt. And try to read it in a non suitable standard font. And afterwards I have to delete the file. Instead I could have easily read the code right here on the forum. It shouldn't be about how much effort I want to put in being able to read your code. The effort burden is on you.

Johan_Ha:
No. I also have to open it with a proper app. Or at least change the extension from ino to txt. And try to read it in a non suitable standard font. And afterwards I have to delete the file. Instead I could have easily read the code right here on the forum. It shouldn't be about how much effort I want to put in being able to read your code. The effort burden is on you.

Reply #5

Johan_Ha:
No. I also have to open it with a proper app. Or at least change the extension from ino to txt. And try to read it in a non suitable standard font. And afterwards I have to delete the file. Instead I could have easily read the code right here on the forum. It shouldn’t be about how much effort I want to put in being able to read your code. The effort burden is on you.

Try loading it into to PC program called Notebook++, it has templates for various computer languages, including C++.
It offsets and linenumbers.
As an example;
sample.jpg
Tom… :slight_smile:

  duration1 = pulseIn(echoPin, HIGH);

Add a timeout to pulseIn, a few milliseconds is probably enough - just see how long it takes for the round trip of a soundwave at a bit more than the maximum distance you will ever have to measure. That'll make your robot much more responsive, instead of waiting for 1 second(!) before the function times out if there's no echo coming back to the sensor.

@TomGeorge, I'm using my phone or tablet for reading this forum. The question is, why should I have to download anything, when anything of interest could be viewed in a browser window.

Johan_Ha:
@TomGeorge, I'm using my phone or tablet for reading this forum. The question is, why should I have to download anything, when anything of interest could be viewed in a browser window.

Hi, fair enough, but there are so many different platforms out these days, who knows what the forum is being viewed on.
I use a Laptop, don't use a portable entertainment center, I have a galaxy IV pad, hardly use it except when V8 and F1 is on the TV.
As for the code, why isn't the NewPing library being used to take care of the UltraSonics?
Tom... :slight_smile:

TolpuddleSartre:

 servo1.attach(3);

...
  pinMode(3, OUTPUT);
...
    analogWrite(3, shim1);


I see that as being a problem.

Yes, for sure, I forgot to change the pin)

TolpuddleSartre:

void RIGHT() 

{
  analogWrite(3, HIGH);
  delay(260);
  analogWrite(3, LOW);
}

void LEFT()
{
  digitalWrite(11, HIGH);
  delay(220);
  digitalWrite(11, LOW);
}



analogWrite (3, HIGH) is a very, very low duty cycle.

Look at the differences between LEFT and RIGHT

Delay? I specifically picked up a certain time for my robot to turn to the right / left and the delays between these sides are different, because these are different motors (this already depends on the quality of the electric motor) and they have different PWMs, so the time for turning is different (I tried to make a turn about 90 degrees). All the same thanks for the answer)