# Move servo randomly within a defined range

Hi all. I am new to arduino and am trying to work with servos. I want the servo to move to a random point within a defined range, eg: servo range to be 30 deg to 150 deg. The servo must now move to a random point between the range. Ultimately I wish to move 2 servos (vertically and horizontally) randomly. So the desired effect would be a range in the shape of a square, within which the servo can move randomly (vertically & horizontally). How would one go about programming this? Any help will be appreciated.

Look at the servo library and start by doing a few examples to get the hang of things:-

Look in the reference section of the IDE under the help menu and see how the random function works.

You should be well on your way then.

Thanks Mike! Got it working randomly within 1 range both V & H. How would you define 3 ranges and and get the servos to randomly select 1 of the 3 ranges, within which it would then move randomly within that ranges parameters? eg: Range 1 = 15 deg to 30 deg, Range 2 = 45 deg to 60 deg, Range 3 = 75 deg to 90 deg. The servo must now randomly select one of the ranges THEN move to a random position within that particular range. Weird?? I know, but this project requires this. Thanks.

The random function can return a value within a range:-
http://arduino.cc/en/Reference/Random

Hi Mike. Hope you can help me out. I don't think I explained myself well thus far. Maybe an illustration will help:

So here's how I want it to work. Total area is in blue. I have divided this into ranges (red). Ranges will not span the entire area, just sections of it.
Step 1 - RANDOMLY select a RANGE. STEP 2 - RANDOMLY Select a random position anywhere in the selected range. Positions will span the entire area of the range.

I can get it to select a random position, but how do we first select a random range.

Any help will be appreciated

Calculate one random number to choose a red range.
Then calculate another random number to choose a position within the chosen red range.

Thanks Mich. I am relatively new to this so is it possible to explain how to go about this, or point me to an example sketch? Thanks

Declare another variable, perhaps called myServoRange, and then use random() to generate a number between 1 and 3 inclusive, or as it would be coded `myServoRange = random (1,4)`. Then use switch case to act according to which range was randomly picked:

``````switch (myServoRange) {
case 1:
//use random to make a position in between 15 and 30 or whatever
break;
case 2:
//use random to make a position in range 2
break;
default:
// if nothing else matches, use random to make a position in range 3
// default is optional
``````

Something like that should do the trick....

Thanks Jimbo!! Worked nicely.