Turning left or right randomly

I am trying to create a code that makes my car turn randomly left or right. I managed to create a code that can only make it go forward, I understand the concept of making the car turn by turning off one motor but I just can't seem to figure out how to make them randomly turn left or right.
This is my code currently:

#define drive 11 //sets pin 11 for first motor
#define fwd 10 //sets pin 10 for drive to go forward
#define bkw 9 //sets pin 9 for drive to go backward
#define drive2 6 //sets pin 6 for second motor
#define fwd2 5 //sets pin 5 for drive2 to go forward
#define bkw2 3 //sets pin 3 for drive2 to go backward

void setup() {
  
  pinMode(drive, OUTPUT);
  pinMode(fwd, OUTPUT);
  pinMode(bkw, OUTPUT);
  pinMode(drive2, OUTPUT);
  pinMode(fwd2, OUTPUT);
  pinMode(bkw2, OUTPUT);
  //max speed for both motors
  analogWrite(drive, 255);
  analogWrite(drive2, 255);

}

void loop() {
  
  digitalWrite(drive, HIGH); //turns on first motor
  digitalWrite(drive2, HIGH); //turns on second motor
  digitalWrite(fwd, HIGH); //makes drive go forward
  digitalWrite(fwd2, HIGH); //makes drive2 go forward
  digitalWrite(bkw, LOW); //stops the backward function
  digitalWrite(bkw2, LOW); //stops the backward2 function

}

Note: I am using a L293D chip to control and I have DC motors from the simple Arduino Kit

if (random(2) == 0) turn_left();
else turn_right();
3 Likes

Figured it out thanks.

Your two-wheel car has nine possible movements, so rather than "0 = left, 1 = right"... why not try using a switch(random):case to pick one of nine...

switch (random(9)) { // oops!  should be 0 to 8... thank you @nolasca
  case 0: forwardSkidLeft(); break;
  case 1: reverseSkidRight(); break;
  case 2: forwardSkidRight(); break;
  case 3: reverseSkidLeft(); break;
  case 4: rotateLeft(); break;
  case 5: rotateRight(); break;
  case 6: forward(); break;
  case 7: reverse(); break;
  case 8: allStop(); break;
}

random(9) will not give you case 9:

max: upper bound of the random value, exclusive.

see

Presumably you want the car to go straight most of the time.
Pick probabilities for each action, use a much larger random number, and have ranges of values cause specific behaviors.

This brings up memories of exploring the city. Flip two coins (these were ancient monetized trading devices), head/head = left, tail/tail = right, head/tail straight. No backwards. "T" no straight. "5-points" two rounds.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.