How can I?

I want to run a program every few minutes with cron. I read a file of times that I expect pins on or off and then check the state of each pin and set them accordingly.

It works fine and leaves the pins in the last set state on program exit. The problem is that it seems like opening the pin causes it to go low. Then it checks the state and goes high (or low as the case may be). This causes my relays to cycle every time.

public State(double onTime, double offTime, String name, GpioController gpio, int pinNum) {
        this.onTime = onTime;
        this.offTime = offTime;
        this.name = name;
        this.pinNum = pinNum;
        //this line must be setting the pin low
        pin = gpio.provisionDigitalOutputPin(getPin(pinNum), name);

    public final void check(double now){
        boolean onNow = (onTime < now && offTime > now);

            log(pin.getName() + " " + pin.getState()  + " before switch");
            log(pin.getName() + " " + pin.getState()  + " after switch");

//for the curious, I have to do this to get the pin from an int
private final Pin getPin(int p) {
    switch (p) {
        case 0: return RaspiPin.GPIO_00;

I can obviously just put a TimerTask in my prog and that works fine when I run from the command line but not using @reboot in the (sudo) crontab. That's because I block the exit with a loop (read 'q' from console) and I'm guessing there is no console.

My last option is to figure out the daemon stuff from apache and do that, but it seems like overkill.

1 Answer 1


Just for an update, I've tried looking through the source and it goes to a native call and I got lazy. The whole reason to use pi4j is my aversion to C. There's another problem in that you can really only have one pi4j program running as starting another one erases some .so file and breaks the running program.

I've solved the problem for my specific situation by using one program that does everything and implementing a Socket. Socket.accept() will prevent the program from exiting and I can control it much easier than using SIGHUP or other signals.

Socket.accept doesn't seem to use any more clock cycles than Thread.sleep, so no electrons are harmed using this method.

I was able to control everything from halfway around the world. I learned this by watching 24 so I know how to 'open a socket'. Not much coding to do in java either. If anyone needs a multi-threaded socket solution in messy, pre-alpha uncommented code, let me know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.