How can i make my code faster?

Hi everyone! i am builting a 4WD bluetooth controled robot using Arduino mega. I have attached my code as word file you can see.

So the problem is with ‘case p’ (marked with red colour). This allows the robot to move autonomous, it’s in a loop until the robot receives another Bluetooth order. The thing is that then it moves to an obstacle and it passes the 20 cm which is the set limit to stop and recalculate course, it needs approximately 3 seconds to stop. And 3 seconds is a disaster. It crashes every time … Is there any way to make the code run faster or ‘case p’ to loop faster?
All ideas are welcome. Thanks in advance!

Robot code 1.doc (112 KB)

I have attached my code as word file you can see.

Wrapping a text file in a Word document just about guarantees that no one will open it.

well

  • don't post a word file!
  • make sure the code you provide is properly compiling and formatted; clearly in what you send it cannot compile because of a missing parenthesis in the loop() function for digitalWrite(trigPin2, LOW;
  • are you sure this is your code, or something you got from somewhere? do you understand what it does?

to improve speed:

  • get rid of all the delays when you print to your TFT.. that will already make your loop faster
  • you are reading tons of stuff at every loop like your GPS coordinate, the humidity, the temperature etc and you don't do anything with it but display it on the TFT... do you REALLY need to read the temperature or humidity every few milliseconds? do you think it's a key attribute of your program and do you think they change that fast?
  • if you don't want to bump into an object, in your forward() function, don't go so fast when you are close to the object... you maintain a static speed whatever the distance is... plan to slow down if distance to object is diminishing...

Ηι J-M-L.
I copied the code from the .ino file to word file because I thought I would be easier to view (I will not do it again…). After I copied the file a erased same of the comments I made for me which would be no use for those who will read the code and this is why there are ) missing. Same parts of the code, like the code for gps I took it from somewhere else, but most of the code is mine… I will try your suggestions. Thanks!

ok - no worries, but when you look for help, make it easy for the people who will spend personal time trying to understand what you do (and do your homework first - i.e. ensure what you post is usable).

if it is too long to post in line with the </> bracketing too, attach directly the .ino - word is a proprietary microsoft format and not suited for programming.

if I were you I would first get rid of all the TFT, GPS, Temperature, Humidity code and just focus on the autonomous mode, reading the 3 distance sensors and making the robot do what you want.

then you can start adding in Bluetooth commands to do other things

then if you use GPS (understand impact on timing, getting a location can take time) use it smartly asynchronously

then you can add your TFT and all the bells and whistles. Remember that adding extra hardware will shorten your battery life, make the robot heavier (increase inertia, will slow down with more difficulty).

basically - start small and build incrementally.

good luck

Hi,

Please read the first post in any forum entitled how to use this forum. http://forum.arduino.cc/index.php/topic,148850.0.html then look down to item #7 about how to post your code. It will be formatted in a scrolling window that makes it easier to read.

Thanks.. Tom.. :)

J-M-L i had no intension to make it difficult for you or for anyone willing to help. When I started this project the basic idea was to make a Bluetooth controlled robot (with the capability of autonomous navigation) with an ip web camera mounted so it will move indoors and outdoors sending image from the camera and data from sensors on it. Of course that makes the tft screen and other stuff useless and pointless. I supposed I added them because it was fun. Anyway, thank you for your suggestions. Your idea to slow down if distance to object is diminishing is very promising.

Gia sou Gianni,

while(millis() - start < 1000){    // Every 1 seconds we print an update
    if (feedgps())
      newdata = true;
  }

This alone introduces an at-least 1 second delay to the loop. Why would you want to use while for this?

As other pointed, I would loose reading all of your sensors/GPS etc on every loop. Try to break them into groups and read each group every X loops (where X to be determined based on the time each loop takes to complete).

@nikosk

actually this triggered my interest at first as a potential issue as I was mislead by the comment to the side.

But if you look at the code, start is never updated, so it will do that while loop only the first second of running the program (and at every reset of the arduino) but not at every loop.

it’s not a great practice because the expression “millis() - start < 1000” will still get evaluated at each loop, taking a few microseconds and will always return false (once the 1st second is gone) and things that only need to run once should be in the setup.

the bad news though is that if feedgps has been successful during the first second, then newdata is set to true and gpsdump (which sends info to an OLED display) will get called at every loop…

So I think this code needs just massive simplification, getting rid of all the stuff that is not necessary for driving the robot and then work on some asynchronous screen update stuff that should not take away the priority of driving the robot.

J-M-L:
So I think this code needs just massive simplification, getting rid of all the stuff that is not necessary for driving the robot and then work on some asynchronous screen update stuff that should not take away the priority of driving the robot.

Definitely! Way to much to be done within a single loop…

J-M-L:
But if you look at the code, start is never updated, so it will do that while loop only the first second of running the program (and at every reset of the arduino) but not at every loop.

But it gets, at the begning of each loop():

void loop()
  
  {
    

      bool newdata = false;
      unsigned long start = millis();   <--------- HERE
      while(millis() - start < 1000){    // Every 1 seconds we print an update
        if (feedgps())
          newdata = true;
      }
      if (newdata)
      { 
         gpsdump(gps);
      }

nikosk: But it gets, at the begning of each loop():

you are 100% right.. ignore my comment above.. so much for reading code in word :)

@nikosk

Geia sou Niko!

Breaking sensors in groups and read each group every X loops as you suggested is far beyond my programming skills, so will make my code simpler by removing for example the part that has to do with the GPS and anything else that is not really necessary. Thanks!

You may find some useful stuff in Planning and Implementing a Program. Notice, in particular, how the code is broken into a series of small functions to make development and debugging easier.

...R

@Robin2

Very informative Robin2!I will try to modify code accordingly.Thanks!

So , i created two new void(). One for the 1.8" TFT

void TFTscreen ()
{
 tft.setTextSize(1);
 tft.setTextColor(ST7735_WHITE, ST7735_BLACK);
 tft.setCursor(0,1);   //
 tft.print( "Distanse data:" );
 tft.setCursor(0,10);   //
 tft.print( "Distanse front:" );
   if (distance3 < 5) {
    tft.setTextColor(ST7735_RED, ST7735_BLACK);
  } else if (distance3 < 15) {
    tft.setTextColor(ST7735_GREEN, ST7735_BLACK);
  } else {
    tft.setTextColor(ST7735_BLUE, ST7735_BLACK);
 . 
 . 
 .
 delay( 100 );
 tft.setTextColor(ST7735_YELLOW, ST7735_BLACK);
 tft.setCursor(1,150);
 tft.print("Sound= ");
 tft.print(get_abs_db(NULL, SOUND_PIN));
 tft.print("db");
 delay (30);
}

and one for the GPS code

void GPSmodule ()
{
  {
    
    bool newdata = false;
  unsigned long start = millis();
  while(millis() - start < 500){ 
    if (feedgps())
      newdata = true;
  }
  if (newdata)
  { 
    gpsdump(gps);
  }
}

and then those two void under bluetooth commands:

case 'y':
TFTscreen();                          
break;
case 'u':
GPSmodule();                          
break;

And now the void loop() runs as fast as needed. The robot moves without crashing and I kept all the bells and whistles :slight_smile: :slight_smile: (for now at least)!

So , i created two new void().

You did NOT. You created two new FUNCTIONS. The return type has NOTHING to do with the name of what you created!

@PaulS

Ok PaulS , it's not void() , it's two new functions...Still the problem with the code is solved!