Go Down

Topic: [SOLVED] Trying to Randomly Move a Servo (Read 897 times) previous topic - next topic

codlink

Jun 11, 2012, 02:43 am Last Edit: Jun 11, 2012, 06:06 pm by codlink Reason: 1
Basically I am trying to "blink an eye."  The servo is connect to an eyelid and I want it to blink all the open or closed.  I have a randomized code that moves the servo to random locations.  How would I go about coding this to move it randomly from closed to open without stopping in the middle?

Code: [Select]
#include <Servo.h>

Servo myservo;

int pos = 0;
int delay1 = 0;

void setup()
{
myservo.attach(9);
}
void loop()
{
  pos=random(65,115);
delay1=random(50, 500);
myservo.write(pos);
delay(delay1);
}
//LiNK

WizenedEE

Code: [Select]

bool open = random(2); // open is 0 or 1 ie false or true
// Three ways to do it with varying levels of verboseness
// 1:
if (open) {
  eye.write(120);
}
else {
  eye.write(30);
}
// 2:
eye.write(open? 120 : 30);
// 3:
eye.write(90*open + 30);

codlink

I just don't know enough about writing a program to implement your code.  I guess I will have to keep studying...
//LiNK

dkl65

Code: [Select]
#include <Servo.h>

Servo myservo;
boolean state;

void setup()
{
  myservo.attach(9);
}
void loop()
{
  state = random(2);
  if (state) myservo.write(115); //open
  else myservo.write(65); //close
  delay(random(50, 500));
}

This will randomly either close, or open the eye, and wait a random delay. If you want the numbers to be very random, use http://code.google.com/p/tinkerit/wiki/TrueRandom.
Visit http://www.glenof.webs.com/!

codlink

Thanks dkl65

Haven't looked at boolean yet.  That is where I was stumped. 
//LiNK

JimboZA

@WizEE....

I intuit that the syntax:

Code: [Select]
(open? 120 : 30)

is a test for open, and if it's true return 120, else return 30.

But I can't find the syntax anywhere in the Arduino Reference so I'm intrigued as to where you found out about it. Is it lurking in the reference somewhere that I didn't see?

Arrch


@WizEE....

I intuit that the syntax:

Code: [Select]
(open? 120 : 30)

is a test for open, and if it's true return 120, else return 30.

But I can't find the syntax anywhere in the Arduino Reference so I'm intrigued as to where you found out about it. Is it lurking in the reference somewhere that I didn't see?


Trick from C, not specific to Arduino:
http://en.wikipedia.org/wiki/Ternary_operation

dkl65

You can also try www.cplusplus.com for C++ code reference. The Arduino reference focuses on functions in the Arduino library, rather than C/C++ itself.
Visit http://www.glenof.webs.com/!

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy