Hello Forums!
I have a programming question about some code I found on youTube, controlling four different servos each doing a different to and fro swing.
My question is: How do I make each movement a random time? ex, swing left takes 3 seconds, swing right takes 15, swing left takes 1, swing right takes 7, etc.
Here is my code:
case MOVING_LEFT:
randNumber0A = random(3,5);
Serial.println(randNumber0A);
pos = pos - ((FULLSWEEP / UPDATES_PER_SECOND) / randNumber0A); //COUNTSPERUPDATE
if (pos < MAXLEFT){
state = MOVING_RIGHT;
}
break;
case MOVING_RIGHT:
randNumber0B = random(1,2);
Serial.println(randNumber0B);
//COUNTSPERUPDATE = ((FULLSWEEP / UPDATES_PER_SECOND) / randNumber0); //random time sweep
pos = pos + ((FULLSWEEP / UPDATES_PER_SECOND) / randNumber0B);
if (pos > MAXRIGHT){
state = MOVING_LEFT;
For each state, MOVING_LEFT and MOVING_RIGHT, the random value is assigned before the motion, so it retains the same random value until the Uno is reset.
How do I make it check the value every time and get a new random number for each swing? I'm sure it's a simple fix, I just can't wrap my admittedly feeble mind around it.
Thanks!
To get a more targeted answer, please post your entire sketch, and do not forget to place it inside code tags. Please read these:
Here is the entire sketch:
#include "servos.h"
#include <arduino.h>
#define HOMEPOS 1000
static int pos = HOMEPOS;
long randNumber0A;
long randNumber0B;
#define MOVING_LEFT 0
#define MOVING_RIGHT 1
#define MAXLEFT 800
#define MAXRIGHT 2000
#define FULLSWEEP (MAXRIGHT - MAXLEFT) // must use brackets so divide happens last
long COUNTSPERUPDATE; //(FULLSWEEP / UPDATES_PER_SECOND) / 0.5; //randNumber0; // random time to do a cycle
static unsigned char state = MOVING_LEFT;
void servoLoop0(void){
switch(state){
case MOVING_LEFT:
randNumber0A = random(3,5);
Serial.println(randNumber0A);
pos = pos - ((FULLSWEEP / UPDATES_PER_SECOND) / randNumber0A); //COUNTSPERUPDATE
if (pos < MAXLEFT){
state = MOVING_RIGHT;
}
break;
case MOVING_RIGHT:
randNumber0B = random(1,2);
Serial.println(randNumber0B);
//COUNTSPERUPDATE = ((FULLSWEEP / UPDATES_PER_SECOND) / randNumber0); //random time sweep
pos = pos + ((FULLSWEEP / UPDATES_PER_SECOND) / randNumber0B);
if (pos > MAXRIGHT){
state = MOVING_LEFT;
}
break;
}
servo0.writeMicroseconds(pos);
}
void servoHome0(){
if (pos > HOMEPOS){
pos = pos - COUNTSPERUPDATE;
if (pos < HOMEPOS){
pos = HOMEPOS;
}
}
if (pos < HOMEPOS){
pos = pos + COUNTSPERUPDATE;
if (pos > HOMEPOS){
pos = HOMEPOS;
}
}
servo0.writeMicroseconds(pos);
}
You obviously didn't read enough of the forum rules. Please go back and edit your posts and put the code inside code tags, as I specifically requested. It is not just my request, it's how things work here.