Random timer coding question

Hi this is my first ever Arduino based project.

I'm looking to build a device (controlled by an arduino UNO or similar) to rotate a pistol target on a pole 90 degrees (or a quarter turn) towards the shooter and then back away 90 degrees again at (semi) random times.

The project will use a servo controlled by the arduino to perform the turning of the target.

The idea is that the unit will turn a quarter turn towards the shooter at semi random intervals between say 5-15 seconds, holds for 10 seconds (to be fired at) then turns back waits between 5-15 seconds (randomly) and repeats on a loop ad infinitum.

As a beginner I'm struggling to find an example of similar code that will achieve this random time function. I've done a fair bit of searching for a similar project online, but whether it's a lack of understanding or not I've so far drawn a blank (pun intended).

Any help or ushering in the right direction as far as a similar project to learn from or coding would be much appreciated!

Thanks in advance :slight_smile:

J

Try using random()
https://www.arduino.cc/en/Reference/Random

Seed it with something like an analog read on a floating pin .

Nice one DrAzzy, I'll do a bit of reading around that suggestion and give it a try.

Much appreciated.

You might want to start by modifying the [u]Blink Example[/u], something like this:

digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
delay( random(5000,15000) );     //Hold LED on for between 5 & 15 seconds

(There's actually a 1 millisecond "error" in that code. :wink: )

Now normally... We like to avoid the use of delay(), especially delays longer than a couple of milliseconds. But in your case, you don't need to do anything during the delay time (I think) so you'll be OK.

Good man DVDdoug!

More ideas & further reading for me to do, I like it, and am familiar with the blink sketch.

Thanks

J

turn your target data into a function something like new target data..

void newtargetata (){
angle = random(3+1); //1=90 degrees, 2 = 180, 3 =270, 4 = 360 home position
staytime = random(14+1) //1 to 15 seconds delay time. use delay(staytime*1000);
hidetime = random(//as above);
servospeed = random(//as above);
}

and maybe instead of having real numbers use variables...

int angle = 30;
int newangle;

setup(){}

loop(){
newtargetdata;
servodrive;
score;
}

void newtargetata (){
newangle = random(angle+1);
//blabla
}

Thanks for the advice darthclueless! :slight_smile:

J