Quote:
Originally Posted by Aaron V
Basically my main problem is that I need to pulse solenoids. It's simple to set it open or closed based on other input, but I don't know how to use time as an input. I figure I need threads because I don't want to stop everything else in the code.
Finally I've both seen the wait() function in the object class and the delay() function in the Timer class - I'm not sure which is better to use and which thread it effects.
|
How often are you trying to pulse the solenoids?
Code:
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Solenoid;
public class Pulser implements Runnable {
Solenoid firstSolenoid = new Solenoid(1);
public void run() {
while (true) {
try {
firstSolenoid.set(true);
Thread.sleep(1000); // sleep thread for 1 second
firstSolenoid.set(false);
Thread.sleep(1000); // sleep thread for another second
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
That will pulse the solenoid on for a second, then off for a second. The sleep() function causes the thread to wait (time in milliseconds).
wait() causes the thread to sleep until another thread issues a notify() or notifyAll() command. It doesn't set a specific time to wait for.
You might try replacing the sleep() function with Timer.delay(), I think that would get rid of the try..catch statements.
Code:
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.Timer;
public class Pulser implements Runnable {
Solenoid firstSolenoid = new Solenoid(1);
public void run() {
while (true) {
firstSolenoid.set(true);
Timer.delay(1);
firstSolenoid.set(false);
Timer.delay(1);
}
}
}
To start the thread, you need to tell it to start() somewhere in your main program:
Code:
Pulser pulser = new Pulser();
new Thread(pulser).start();