Arduino is laggy and locks up on RC robot

Hi Everyone,

I've made an RC transmitter and RC tank and am having big problems with the tank receiving (and reacting) to the drive signals. The code has 2 main parts, tank drive, and headlights on/off.

The headlights on/off code works by itself, and when i serial print what the tank is receiving from the transmitter (left joystick, right joystick, headlight mode, drive mode) and its onbaord photoresistor readings, the serial monitor displays it correctly. I can start to see some problem when i move the joysticks, that the serial monitor display slows down.

When i add the code to analogwrite the joystick data to the motors, here's where the big problem is. The robot doesn't respond. I hear the motors whining, but they are not moving. Then out of nowhere they move. Same with the headlights, its as if the arduino receiver is getting overloaded, and then at some random point decides to respond to the data.

Might anyone be able to look at my robot code and figure out which part is causing the arduino to be erratic/unresponsive? I really look forward to solving this and i'm really stumped at the moment.

Just to make the code a bit clearer...

Transmitter
This has a counter called lightMode that counts 0,1,2 when the user presses a button.
Also has a counter called driveMode that counds 0,1,2 when the user presses a button.

Theres also a bunch of code for a "fake" menu system. There are 9 text screens, and when a user presses either the headlightmode or drivemode button, it looks like they are selecting an option from a menu. But in fact the whole display is being changed.

Receiver/Robot
when it receives lightMode 0, it turns the headlights off
when it receives lightMode 1, it turns the headlights on
when it receives lightMode 2, it checks a photoresistor and turns the headlights on if its too dark, and off when its bright enough

when it receives driveMode 0, it lets the user control the robot skid steering using the joysticks
when it receives driveMode 1, (not as yet implemented because i'm having issues just adding the driveMode 0 code) it lets the user control the robot skid steering using the joysticks UNTIL the front Sharp IR sensor detects an obstacle, then it takes away control form the user and reverses, then gives control back to the user.
when it receives driveMode 2, (not yet implemented) the robot drives forward by itself, stops reverses and turns a bit when it encounters an obstacle, then continues forward again.

The robot is just a mish-mash of wires and motors until I can get the code working

I've attached the code, and look forward to as much assistance as possible.

I was inspired by the below instructable to make my robot, but the instructable-robot didn't have proportional steering so i decided to make my own.

The Instructable

TXv12.ino (13.3 KB)

RXv10.ino (4.46 KB)

I have only looked briefly at the shorter RX code. You seem to have almost everything inside the IF

 if (vw_get_message(buf, &buflen))

I suspect that gets in the way of receiving the next message.

And I see lots of PRINT statements - they are slow.
And delay(10) does not help matters either.

IMHO you should break your program into several functions each dealing with a small part of the project. Have a look at Planning and Implementing a Program

If it was my program the code in loop() would look something like

void loop() {
   readWireless();
   moveMotors();
   updateLights();
}

What wireless device are you using?

...R

Hi Robin,

I'm using the super cheap 433mHz modules, that have a max message length of 30 bytes. I'm going to try what you suggested right away and get back to you!

I don't have any 433MHz modules - only nRF24L01+ transceivers. But I think my earlier comments are relevant to both.

...R

Hi,
How are you powering the arduino and the motors and the lights on the RC tank?
Can you please post a copy of your circuit, in CAD or a picture of a hand drawn circuit in jpg, png?

Thanks.. Tom... :slight_smile:

@Robin2

It seems when I put the relevant code into functions...the very first function readWireless() gives me an error saying "X was not declared in this scope." But i don't get it, X is declared in the function itself. And when i move the contents of readWireless() back into the main loop, or the if statement, then the second function gives me an error X not declared Y not declared etc...puzzling. I've attached the newest version of the code, with everything in functions, which is giving me the errors.

@TomGeorge
It'll take me a bit of time to get those drawings ready...but in summary, i'm powering the Arduino from a USB connected to my computer. The headlights and motor driver are connected to a 5V source connected to the wall. Both Arduino 5V and wall 5V grounds are connected. I used 2 power rails so that the Arduino power doesn't drop low when the motors start pulling power...which causes problems like the arduino resetting on its own.

RXv11.ino (3.47 KB)

Ok I made some progress. The robot can turn its headlights on and off as per the mode that is being transmitted to it. And for the drive, i decided to forget about the drive modes and just have the darn thing respond to joystick commands, which it does. But here's a strange phenomena that is happening...

If i push on the right joystick first and hold it, the right motor moves. And while that is happening, if i push on the left joystick the left motor moves.

BUT when i try it the other way around, only the left motor moves. Somehow the left motor is getting priority if the left joystick is pressed first, and the right joystick is being disregarded.

What is even more baffling is that the serial print is working fine, and is showing that robot is receiving the correct values from both joysticks, whatever order they are used.

RXv10.ino (3.76 KB)

I don't see any extra functions in the code in Reply #6

...R

Hi Robin2,

The functions were in reply 5, but then i took them out in the attachment in reply 6, where i sort of made some progress.

Use functions.

(A bit like the song that says "use sun screen")

...R

The problem I'm running into is that in the readWireless() function, it creates variables X and Y (the joystick readings), but then i get an error "X was not declared in this scope. And also, these readings are not available to the moveMotors() function, because they are not global variables.

I wonder if these 433mhz modules, using the virtualwire library, must have everything in the if (data was received) statement and not broken out into proper functions?

Aha! On a whim, i decided to spell out all of the 9 situations that the joysticks could be in...and now the motors spin properly, and theres no priority of one motor spinning and the other not. Also, the serial monitor is spitting out all of the info correctly and the arduino is not laggy and does not lock up! It seems that victory is at hand! but no...

Here's the final strange thing that is going on that is stopping me from finishing this project. Please see the below pictures which illustrate what is happening (I've also attached the code file below).


In the first instance, i have all of the joystick scenarios at the beginning, and then the lightmodes at the end. The headlights do not respond to any commands. Its as if the arduino is only doing the drivemodes and is ignoring the headlights, even though the serial monitor is showing that it is receiving different headlight modes as the user is pressing the button. Why is the arduino receiving the right command but deciding not to act on it?


Now when i put the headlights code at the top, the headlights work correctly. BUT, the drive commands do not work unless the headlights are in the last mode (lightMode==2). its as if the arduino ignores the drive commands unless they come immediately after the lightMode. Why is this happening?

I'm sure this type of thing can be avoided when a program is broken out into functions, but it looks like these cheap 433mHz Tx and Rx, using the VirtualWire library, one has to put the entire code into the "If receving data" statement.

Thanks in advance for looking at this all, I can't wait till this is fixed and i can close this chapter of my arduino life thats been going on since last Christmas.

RXv11.ino (6.89 KB)

Hi,
This is your code in code tags.

#include <VirtualWire.h>

int LeftForward = 3;
int LeftReverse = 5;
int RightForward = 6;
int RightReverse = 11;
int hLight =4;

//int lightMode = 0;              // What mode is the light in?
//int driveMode = 0;              // What mode is the drive in?

int sensorPin = 0; // analong pin that photoresistor is connected to
//int sensorPin2 = 1; // analong pin that Sharp IR sensor is connected to

int lowThreshold = 400;
int highThreshold = 500;

uint8_t data[24];

void setup()
{
  Serial.begin(9600); // Debugging only
  Serial.println("Receiving");
  //  pinMode(13,OUTPUT);
  pinMode(hLight,OUTPUT);
  //digitalWrite(hLight,LOW);
  // Initialise the IO and ISR
  //vw_set_ptt_inverted(true); // Required for DR3100
  vw_setup(2000); // Bits per sec
  vw_set_rx_pin(8);
  vw_rx_start();       // Start the receiver PLL running
}

void loop()
{
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;

  if (vw_get_message(buf, &buflen)) // Non-blocking
  {
    int X = atoi(strtok((char*)buf, ","));  // Look for a comma, the return the data before it.
    int Y = atoi(strtok(NULL, ",")); // same as above
    int lightMode = atoi(strtok(NULL, ",")); // same as above
    int driveMode = atoi(strtok(NULL, ".")); // Look for a period, then return data before it.

    //...
/*        
     int sensorValue = analogRead(sensorPin);      
     Serial.print(X); // X axis
     Serial.print(", ");
     Serial.print(Y); // Y axis
     Serial.print(", ");
     Serial.print(lightMode); // lightMode
     Serial.print(", ");
     Serial.print(driveMode); // driveMode
     Serial.print(", ");
     Serial.print(sensorValue); // photoresistor value
     Serial.print(". ");
     Serial.println();
     delay(10);   
*/     

//............................headlights begin...........................

                 if (lightMode == 0) {          // off
                      digitalWrite(hLight,LOW);               // turn lights off!
                    } 
                    else {
                      if (lightMode == 1) {        // on
                        digitalWrite(hLight,HIGH);             // turn lights on!
                      } 
                      else {
                        if (lightMode == 2) {      // automatic, make the lights dependent on the LDR

                          // Read the sensor pin
                          int sensorValue = analogRead(sensorPin);

                          // If light level is low is detected, switch light on
                          if (sensorValue < lowThreshold){
                            digitalWrite(hLight, HIGH);
                          }

                          // If light level goes up again, switch the lights off
                          if (sensorValue > highThreshold){ 
                            digitalWrite(hLight, LOW);
                          }

//............................headlights end...........................


    //.......................................drive begin.................................................................................... 
    //...........................left joystick forward 3 commands end........................   

    if ((X >= 480) && (Y>=504)){
      X = map(X, 480,960, 0, 255);
      Y = map(Y, 504,976, 0, 255);   
      analogWrite(LeftForward,X);
      analogWrite(LeftReverse,0);
      analogWrite(RightForward,Y);
      analogWrite(RightReverse,0);
    }

    else
    {

      if (   (X >= 480) && (Y>494) && (Y<504)   )   {
        X = map(X, 480,960, 0, 255);  
        analogWrite(LeftForward,X);
        analogWrite(LeftReverse,0);
        analogWrite(RightForward,0);
        analogWrite(RightReverse,0);
      } 


      else
      {
        if ((X >= 480) && (Y<=494)){
          X = map(X, 480,960, 0, 255);
          Y = map(Y, 494,37, 0, 255);  
          analogWrite(LeftForward,X);
          analogWrite(LeftReverse,0);
          analogWrite(RightForward,0);
          analogWrite(RightReverse,Y);
        }
        //...........................left joystick forward 3 commands end........................

        //...........................left joystick zero 3 commands start........................
        else
        {
          if ((X > 470) && (X<480) && (Y>=504)){
            Y = map(Y, 504,976, 0, 255);   
            analogWrite(LeftForward,0);
            analogWrite(LeftReverse,0);
            analogWrite(RightForward,Y);
            analogWrite(RightReverse,0);
          } 
          else
          {
            if ((X > 470) && (X<480) && (Y<504) && (Y>494)){  
              analogWrite(LeftForward,0);
              analogWrite(LeftReverse,0);
              analogWrite(RightForward,0);
              analogWrite(RightReverse,0);
            } 
            else
            {
              if ((X > 470) && (X<480) && (Y<=494)){
                Y = map(Y, 494,37, 0, 255);
                analogWrite(LeftForward,0);
                analogWrite(LeftReverse,0);
                analogWrite(RightForward,0);
                analogWrite(RightReverse,Y);            
              }
              //...........................left joystick zero 3 commands end........................

              //...........................left joystick reverse 3 commands start........................

              else
              {
                if ((X <= 470) && (Y>=504)){
                  X = map(X, 470,19, 0, 255);
                  Y = map(Y, 504,976, 0, 255);   
                  analogWrite(LeftForward,0);
                  analogWrite(LeftReverse,X);
                  analogWrite(RightForward,Y);
                  analogWrite(RightReverse,0);  
                }

                else
                {
                  if ((X <= 470) && (Y<504) && (Y>494)){
                    X = map(X, 470,19, 0, 255);  
                    analogWrite(LeftForward,0);
                    analogWrite(LeftReverse,X);
                    analogWrite(RightForward,0);
                    analogWrite(RightReverse,0);    
                  }

                  else
                  {
                    if ((X <= 470) && (Y<=494)){
                      X = map(X, 470,19, 0, 255);
                      Y = map(Y, 494,37, 0, 255);   
                      analogWrite(LeftForward,0);
                      analogWrite(LeftReverse,X);
                      analogWrite(RightForward,0);
                      analogWrite(RightReverse,Y);   
                    }
                    //...........................left joystick reverse 3 commands end........................
                    //.......................................drive end....................................................................................  


   
                        }
                      }
                    }  
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

You need to structure your sketch to minimize the amount of motor control instructions.

You need to use functions to;

  • Lights Control
  • Left Motor Stop
  • Left Motor Fwd
  • Left Motor Back
  • Right Motor Stop
  • Right Motor Fwd
  • Right Motor Back

You could also do the same for the joystick position.

  • function to detect x left
  • function to detect x right
  • function to detect x middle
  • function to detect y left
  • function to detect y right
  • function to detect y middle

each function returning a string like LF LB LM RF RB RM

Or they each return a constant 101 102 103 and 201 202 203
Then use switch case function to select the two motor control functions that are sent.

Hope it makes sense... look at how functions work.. Tom... :slight_smile:

exwhyzed:
The problem I'm running into is that in the readWireless() function, it creates variables X and Y (the joystick readings), but then i get an error "X was not declared in this scope.

Fix this problem. Don't abandon the concept of functions.

Post the latest code you have with functions and let's see if we can help with that.

...R

After many different configurations, I managed to get error-free code, but it doesn't work properly. The motors spin by themselves and do not respond to the joystick...and the headlights don't work. BUT, the correct information is displayed on the serial monitor which means that the robot is receiving the correct information from the RC transmitter.

The X and Y and lightMode variables were declared in the loop, and were not being seen by the functions, so i went ahead and declared them at the top of the file. Thanks in advance for any and all suggestions!

RXv12.ino (5.62 KB)

Yaay! Ok it seems after i retraced every curly bracket... i rearranged a couple of them and now the code works. Perhaps some of the motor code was included in some of the headlights code.

I think for all future projects I will use functions, but for these 433mHz Tx/Rx using the VirtualWire library, I'll have to jam everything into the IF statement. Now all i have to do is implement the driveModes and i'm set.

Thanks Robin2 and TomGeorge!

I couldn't live with myself for abandoning functions and have spent many hours trying to solve this enigma and I'm very close.

updateLights() - this function works
userMotors() - this function takes transmitter joystick readings and moves the motors accordingly, this function works

moveMotors() - This is the function that is giving me major problems, such as unresponsive motors.

To test my code, i put updateLights() and userMotors() in the loop, and the RC Robot worked as it should.

But when i now comment out userMotors() and bring in moveMotors(), only the headlights work and not the motors.

What i really don't get is that in the moveMotors() code, i put the userMotors() code for all 3 modes that the robot could be in. And it still doesn't move when i press the joysticks. The robot is always in one of three modes, so i don't get why it doesn't move when each mode points to working code.

I've attached the latest working code that is broken into functions, and would really appreciate a second pair of eyes to review it and point out the error(s) that I can't see. Thanks!

RXv13.ino (10.4 KB)

Well, scanLeft and scanRight look very similar.
If they returned values, rather than assigning to globals, maybe they could be rewritten as a single function.
Also,

void motorWrite (int leftFwdVal, int leftRevVal, int rightFwdVal, int rightRevVal)
{
  analogWrite(LeftForward, leftFwdVal);
  analogWrite(LeftReverse, leftRevVal);
  analogWrite(RightForward, rightFwdVal);
  analogWrite(RightReverse, rightRevVal);  
}

void stopMotor()
{
  motorWrite (0,0,0,0);
}

void backward()
{
  motorWrite (0, 175, 0, 175);
}

void left()
{
  motorWrite (0, 175, 175, 0);
}

void right()
{
  motorWrite (175, 0, 0, 175);
}

exwhyzed:
moveMotors() - This is the function that is giving me major problems, such as unresponsive motors.

I don't understand why you are getting data using vw_get_message(buf, &buflen) in the moveMotors() function. In my concept that should be in a getData() function or equivalent.

The moveMotors() function should just make the motors do their thing based on whatever data has already been gathered. That way the moveMotors() function will neither know nor care whether the data came via VirtualWire or just from values that you enter in the program for testing.

And, as far as I can see, your useMotors() function is pretty much the same as what you used to have in loop() without any attempt to separate out different activities each into its own function.

...R

@AWOL
thats an interesting idea, I hadn't thought of combining them before, and i think it'll be my next step once i get this robot working

@Robin2
Your suggestion got me over another hurdle, thanks! I was positive i tried every combination of commenting in/out that line in every function but i guess everyone has blindspots. This latest iteration of the code, it compiles without error and sort of works in a laggy and unpredictable way. I start off the project with the transmitter sending the message for "headlights on" , but the robot takes a little while before turning on its lights...unlike in the past when the code was less complicated, the headlights turned on right away. Also the robot isn't properly responding to the joysticks, and seem to get stuck in whichever way i press the joystick. Also, the override command is getting triggered even though there is nothing in front of the Sharp IR sensor.

I think at this point I've spent too many hours on this, and have been pestering this forum too much. its also taking time away from other peoples problems being solved.

I know the solution must be a few lines of code, but its too far out of my reach. I can pay $30 US if anyone is interested.

I'll post the RC transmitter code and RC receiver (the robot) code below.

Thanks in advance Robin2, TomGeorge and AWOL for all of the help you've provided, it was and is much appreciated!!

So to summarize what i'm looking for...The transmitter sends the following information to the robot:
-left and right motor controls, via joystick movements

  • headlight mode
    0 ... off,
    1 ... on
    2 ... automatic, depending on the value of the photoresistor

-drivemode
0 ... user controls the robot
1 ...- mixed (user control until IR sensor says obstacle is too close, then robot takes control away from the user, backs up, scans left and right, and points in the direction with greatest distance)
2 ...robot has full control. it will move forward on its own until the ir sensor says theres an obstacle in the way, then the robot will back up, scan left right, and pick the best direction and proceed driving forward.

My whole project is basically THIS instructable robot, but with proportional control of the motors, and the added lightmodes and drivemodes. I"m using the same cheap wireless system as that instructable. I'll include the code for that robot below as well. Thanks greatly for anyone who take take up this offer to help me get my robot working.

TXv12.ino (13 KB)

RXv16.ino (10.1 KB)

Instructable Robot Rx.ino (7.03 KB)