Line Follower: can my code be optimized?

Hello everyone,

I recently started building a Line Follower for an university project using an Arduino Nano V3 (ATmega328) but I've ran into a problem. We had to implement a countdown (5 seconds) before the car starts moving (that's the use of the for loop) but if I try to write Motor(-120,-120) in my function that controls the steering my Arduino resets and counts down again from 5. The build in white led ('pin' 13) on my arduino blinks as well, as if I interrupted power.

Are there any mistakes in my code? Below a summary of what I'm trying to achieve
EDIT: Thanks to PaulS, I realized my code was in an entirely wrong format/structure, so I reprogrammed the entire thing:

int Red = 7;        // Red Led
int Green = 8;      // Green Led
int Blue = 9;       // Blue Led

int RForward = 5;
int LForward = 6;  
int LBackward = 10;
int RBackward = 11;

int SensorL;    // Value of A1 (left sensor) will be assigned to this variable
int SensorLM ;  // Value of A2 (midleft sensor) will be assigned to this variable
int SensorM;    // Value of A3 (mid sensor) will be assigned to this variable
int SensorRM;   // Value of A4 (midright sensor) will be assigned to this variable
int SensorR;    // Value of A5 (right sensor) will be assigned to this variable

int Base;       // Basespeed used in the engine function; Motor(L,R)
int Pot;        // Potentiometer (Raw data from A0)
int Pot135;     // Mapped value from potentiometer
int LF; int RF;


void setup() {
pinMode(Red,OUTPUT); pinMode(Green,OUTPUT); pinMode(Blue,OUTPUT); 
pinMode(RForward,OUTPUT); pinMode(LForward,OUTPUT); pinMode(RBackward,OUTPUT); pinMode(LBackward,OUTPUT);

for(int Led = 0; Led < 5; Led++){
  delay(500); digitalWrite(Red,HIGH); delay(500); digitalWrite(Red,LOW); 
  if(Led > 3){digitalWrite(Green,HIGH);}
  }
}

void Motor(int L,int R){
  if((L >= 0) && (R >= 0)){
    LF = (L + Base);
    RF = (R + Base);
  }
  else{
    LF = L;
    RF = R;
  }
  
  if(L >= 0){                        // Instructions for the left wheel
    analogWrite(LForward,LF);
    analogWrite(LBackward,0);
  }
  else{
    analogWrite(LBackward,abs(L));
    analogWrite(LForward,0);
  }
  
  if(R >= 0){                        // Instructions for the right wheel
    analogWrite(RForward,RF);
    analogWrite(RBackward,0);
  }
  else{
    analogWrite(RBackward,abs(R));
    analogWrite(RForward,0);
  }
  
  if(L != R){                        // If one of the wheels turns different compared to another
    digitalWrite(Blue,HIGH);         // the blue led will light up instead of the usual green one
    digitalWrite(Green,LOW);
  }
  else{
    digitalWrite(Blue,LOW);
    digitalWrite(Green,HIGH);
  }
}


void loop() {
  Pot = analogRead(A0);
  Pot135 = map(Pot,0,1023,60,135);   // Basevalue is 60, because the wheels block if driver input (PWM) is below 60
  
  if(Pot > 0){
    Base = Pot135;
  }
  else{
    Base = 0;
  }
  
  SensorL  = analogRead(A1);         // Values read from the infrared sensors (Left, Midleft, Mid, Midright, Right)
  SensorLM = analogRead(A2);
  SensorM  = analogRead(A3);
  SensorRM = analogRead(A4);
  SensorR  = analogRead(A5);
  
  /* This is where the 'if' statements will be written that steer the car, something like this:
  if(SensorM > 680){
    Motor(0,0);} 
    
    -and so on. If the received value is above 680, the mid-sensor is on the black line it
    is supposed to follow, so no corrections should be made. The rest of the steering controls will be similar,
    they will all use the Motor() function to steer the vehicle around. I'm still thinking of implementing the potentiometer
    value in the Motor() function, as the steering needs to happen faster when the car's going faster as well.
  */
}

I threw my code in as an attachment as well.

What I'm trying to do:
Make a car that follows a black line, by using infrared sensors to notice if it's nearing the white paper or on the black line. I'm using an array of 5 sensors and a potentiometer to control the speed at which the car moves.

What goes wrong:
So far, most of the problems have been solved. Although one wheel tends to rotate faster than the other depending which one receives it's write earlier. If the left wheel is written to first, it'll spin faster. I already tried replacing the motor driver, pwm pin,...
Overall, all that remains now is fully optimalizing my code, any ideas? Feel free to share!

EDIT: Thanks to CrossRoads, I now know that my board resets when the driver board requires peak power, This is the cause of the Motor(-120,-120) problem as well. Karma+!

The Arduino board that I'm using:

The driverboard for controlling the motors:
http://www.lctech-inc.com/Hardware/Detail.aspx?id=155c73e2-e972-473f-913d-ec443dbef0be

Thanks in advance people, I could really use the help of more experienced people than me as I'm new to programming. :cold_sweat:

Attachments: Code, schematic, pictures

Second_Line.ino (3.05 KB)

How is the motor powered? It is likely drawing too much power, which makes the supply voltage drop and causing a reset.

Especially prevalent when the motor makes a sudden change in direction.

I'm able to rotate the wheels forward at max speed (PWM 255), backwards,.. anything I can imagine except for two wheels backwards at the same time. It just stops and resets.

As for power, I'm putting 10,5V on the Vin of my board as well on the driver board I got.

The driver board is this one :
http://www.lctech-inc.com/Hardware/Detail.aspx?id=155c73e2-e972-473f-913d-ec443dbef0be

In my loop() , I can write:

Motor(120,0);
delay(500);
Motor(-120,0);
delay(500);

It works, the wheels rotate in order changing direction over and over again without the board resetting , but when I try:

Motor(-120,-120);

or

Motor(-120,120);
delay(500);
Motor(120,-120);
delay(500);

The whole thing resets :frowning:
Thanks for replying by the way! I appreciate it alot

if(LF > 50){(LF - 17);}  // This is because one of the wheels turns to fast for some unknown reason, it's not the driver, pwm pin, motor,..

Useless code.

Please do not put multiple statements on one line. No professional programmer does that. No professional programmer puts the } on the same line as anything else. Correcting those issues, you have:

if(LF > 50)
{
   LF - 17;
}  // This is because one of the wheels turns to fast for some unknown reason, it's not the driver, pwm pin, motor,..

which, I hope, makes it clearer that the code in the block is useless.

What happens if you use Motor(-120, 120) followed by Motor(0, 0) followed by Motor(120, -120) with delays in between. Perhaps the sudden change in direction of both motors causes the power surge that kills the Arduino.

Oh, I'll try my best, thanks.

If I try:

Motor(-120,120);
delay(200);
Motor(0,0);
delay(200);
Motor(120,-120);
delay(200);

It resets after doing the loop once, if I plug in my USB cable while the battery is in as well, this does not happen and the board continues to operate. But if I unplug the USB again (battery power only: 10.5V), the board does void setup (), but resets after finishing. So it does void setup over and over again.

This only changes if I unplug the battery, and rewrite the code to the board.
Also, am I supposed to connect my board to usb and battery at the same time? The battery is connected to Vin(+) and GND(-).

Thanks so far

If I try the following in my void loop() (battery power only, no usb whatsoever):

Motor(-120,120);
delay(1000);
Motor(0,0);
delay(1000);
Motor(120,-120);
delay(1000);

The board starts acting weird again, and does it's void setup() again and again because it seems to reset.
If I try Motor(120,120) for example, everything works like it should

I took an identical Arduino Nano V3 and wrote the same code to it, with this in my void loop():

Motor(-120,120);
delay(1000);
Motor(0,0);
delay(1000);

And the wheels rotate like they should, if I do the same with the other board it starts acting weird again. (looping the setup)
Does this mean I've fried my first Arduino board? Crap :astonished:

Once again - how is it wired up? Post a schematic. Draw it, take a photo, resize to ~1000 wide, post it.

I'll post a picture on how it looks irl in just a second, this is a quick sketch to start with

The driver is in the right bottom, the battery holder is in the middle (black) as well as a 1.5V battery at the top (two in series), the potentiometer is at the top right and the Arduino board in the top left.

The infrared sensors are at the bottom between the wheels.

Thanks so far, I realize my answers/questions were not very structured, apologies.

EDIT: Images moved to attachments

Some of us can't access that website.
Modify your post, click Addtional Actions, Browse to your locally stored file, and Attach the file.

Done :slight_smile:

I'm gonna stick with 1 battery powering both Vin and Motor Driver as being the culprit.
Motor sucking down the voltage and resetting the Arduino.
9V little square batteries only good for a couple hundred mA, will drain pretty quick.

Those look like the sparkfun geared motors you find in this kit?

4 AA work better to power a motor shield.

Jup, those are the electric motors we got, that's also the example the teacher used. We're supposed to construct our car fully by ourselves. I used MDF (medium density fibreboard) as a base.

I'll look into using AA batteries, you're right, 9V batteries probably don't suffice regarding amps.