# DC motor random

I would like to know how to run a DC motor at random speeds and random direction.

-steve

Use a random number generator to provide control values?

I have a sketch for some RC servos (continuous rotation), which can be controlled by the user with potentiometers, forward and reverse, and I also have a switch to a random mode, where the servos respond to random values....

Partial code here:

``````else
{
unsigned long newMillis = millis();
if (newMillis - prevMillis > interval)
{
prevMillis = newMillis;

int pos = random(80, 100);
int pos2 = random(50, 130);

servo1.write(pos);
servo2.write(pos2);
}
}
}
``````

I have this bridge sketch and I'd like to do something similar with DC motors. This has forward and reverse switches and a speed control pot. This is all user controlled, but I'd also like to switch to a sketch where the motors to vary with random speeds and random direction.

Does this help? lemme know....

-steve

`````` const int switchPin = 2;    // switch input
const int motor1Pin = 3;    // H-bridge leg 1 (pin 2, 1A)
const int motor2Pin = 4;    // H-bridge leg 2 (pin 7, 2A)
const int enablePin = 9;    // H-bridge enable pin

void setup() {
// set the switch as an input:
pinMode(switchPin, INPUT);

// set all the other pins you're using as outputs:
pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
pinMode(enablePin, OUTPUT);

// set enablePin high so that motor can turn on:
digitalWrite(enablePin, HIGH);
}

void loop() {
// if the switch is high, motor will turn on one direction:
digitalWrite(motor1Pin, LOW);   // set leg 1 of the H-bridge low
digitalWrite(motor2Pin, HIGH);  // set leg 2 of the H-bridge high
}
// if the switch is low, motor will turn in the other direction:
else {
digitalWrite(motor1Pin, HIGH);  // set leg 1 of the H-bridge high
digitalWrite(motor2Pin, LOW);   // set leg 2 of the H-bridge low
}
}
``````
``````  analogWrite (enablePin, randomvalue) ;
``````

To have the motors spin in a random direction, you will need an H-Bridge to allow them to run in reverse. This is a reference page for random functions, it may have some info on what you are looking for: https://www.arduino.cc/en/reference/random Hope that helps!