# Random movement via, Millis

I'm trying to understand how to incorporate A random statement into a Millis function I have set up for random sounds to add a motor movement.

I have a motor where I am using a tb6612fng, to rotate a motor on my robot. In my sketch I use the Millis function to have a random sound play via a DFplayermini every min, and I want that to correspond with a head movement. perhaps using something like:

``````randomSeed( analogRead(A0) );
``````

(trying to Keep it truly random)

After I added the movement into the statement, I realize its to structured and I'd like to to do one of maybe a few pre-programed movements.

can someone help explain to be a good way and how I would set-up a group of set movements and use random within the millis statement to call upon one of these?

example of the Motor statements I'd like to be random:

``````//Movement one:
motor1.drive(255,200);
motor1.drive(-255,200);

//Movement two:
motor1.drive(-255,200);
motor1.drive(255,200);
``````

My millis statement I'd like the random movement to happen within:

``````const unsigned long eventInterval = 60000; // 90000= 1.5 min change value to change chatter time
unsigned long previousTime = 0;
int randomInt;

unsigned long currentTime = millis();

if ( currentTime - previousTime >= eventInterval) { // delay event for R2s "chatter" sounds folder 01

randomInt = random(1, 144);  //number of tracks in folder on Sd card
myMP3.playFolder(1, randomInt); //Plays random track from dfplayer
previousTime = currentTime;
}
``````

I would write a function that you can call from loop(). I'm not sure how well the below combines with your MP3; if that is blocking, it will probably not work that well. I think it's self documenting.

``````void loop()
{
moveIt();

// MP3 stuff here
...
...
}

void moveIt()
{
// variables that will be remembered

// last time that a movement is done
static unsigned long lastUpdateTime;
// desired random interval
static unsigned long interval;
// which move to do
static byte moveSelect = 0;

// if it's time
if (millis() - lastUpdateTime >= interval)
{
// do the move
switch (moveSelect)
{
case 0:
//Movement one:
motor1.drive(255, 200);
motor1.drive(-255, 200);
break;
case 1:
//Movement two:
motor1.drive(-255, 200);
motor1.drive(255, 200);
break;
}

// set a new interval between 1 and 2 seconds
interval = random(1000, 2000);
// remember when the movement was done last
lastUpdateTime = millis();

// indicate which movement next
moveSelect++;
if (moveSelect == 2)
{
moveSelect = 0;
}
}
}
``````

If you have more than a few movements, the switch statement will become big. In that case you're better of using arrays and using moveSelect as an index.

Note:
The use of static variables allows the function to be stand-alone without dependencies on global variables. Motor1 is still a global variable though.