private void configurePin() {
    Pin pin = (Pin) findPin(config.pinNumber().getVal());

    unprovision(pin);
    switch (config.pinType()) { // Get request sets the input pin
      case input:
        GpioPinDigitalInput digitalIn = this.gpioContoller.provisionDigitalInputPin(pin);
        switch (config.pinLevel()) {
          case high:
            digitalIn.setPullResistance(PinPullResistance.PULL_UP);
            break;

          case low:
            digitalIn.setPullResistance(PinPullResistance.PULL_DOWN);
            break;
        }
        break;
        // Post request sets the output pin
      case output:
        GpioPinDigitalOutput digitalOut = this.gpioContoller.provisionDigitalOutputPin(pin);

        switch (config.pinLevel()) {
          case high:
            digitalOut.setState(true);
            break;
          case low:
            digitalOut.setState(false);
            break;
        }
        break;
    }
  }
  @RequestMapping("/left.html")
  public String left() throws InterruptedException {

    leftFrontMotor.toggle();
    rightFrontMotor.toggle();

    return "Moving left...";
  }
  @RequestMapping("/back.html")
  public String back() throws InterruptedException {

    leftBackMotor.high();
    rightBackMotor.high();

    return "Moving backwards...";
  }
  @RequestMapping("/forward.htmlc")
  public String forward() throws InterruptedException {

    leftFrontMotor.high();
    rightFrontMotor.high();

    return "Moving forward...";
  }
Example #5
0
  @Override
  public GpioPinDigitalOutput provisionDigitalOutputPin(
      GpioProvider provider, Pin pin, String name, PinState defaultState) {
    // create new GPIO pin instance
    GpioPinDigitalOutput gpioPin = provisionDigitalOutputPin(provider, pin, name);

    // apply default state
    if (defaultState != null) {
      gpioPin.setState(defaultState);
    }
    // return new new pin instance
    return gpioPin;
  }
Example #6
0
 @Override
 public void pulse(long milliseconds, GpioPinDigitalOutput... pin) {
   if (pin == null || pin.length == 0) {
     throw new IllegalArgumentException("Missing pin argument.");
   }
   for (GpioPinDigitalOutput p : pin) {
     // ensure the requested pin has been provisioned
     if (!pins.contains(p)) {
       throw new GpioPinNotProvisionedException(p.getPin());
     }
     // toggle pin state
     p.pulse(milliseconds);
   }
 }
Example #7
0
 @Override
 public void setState(PinState state, GpioPinDigitalOutput... pin) {
   if (pin == null || pin.length == 0) {
     throw new IllegalArgumentException("Missing pin argument.");
   }
   for (GpioPinDigitalOutput p : pin) {
     // ensure the requested pin has been provisioned
     if (!pins.contains(p)) {
       throw new GpioPinNotProvisionedException(p.getPin());
     }
     // set pin state
     p.setState(state);
   }
 }
Example #8
0
  private void sendActivePulse() {
    try {
      trigPin.low();
      Thread.sleep(300);

      trigPin.high();
      Thread.sleep(10);

      trigPin.low();

    } catch (InterruptedException e) {
      System.out.println("Interrupted exception");
    }
  }
  @RequestMapping("/shutdown.html")
  public String shutdown() {

    gpio.shutdown();
    leftBackMotor.low();
    leftFrontMotor.low();
    rightBackMotor.low();
    rightFrontMotor.low();
    gpio.unprovisionPin(leftBackMotor);
    gpio.unprovisionPin(rightBackMotor);
    gpio.unprovisionPin(rightFrontMotor);
    gpio.unprovisionPin(leftFrontMotor);

    return "Program was shutdown correctly";
  }
  @Test
  public void testTriggerLow() throws InterruptedException {
    provider.setMockState(MockPin.DIGITAL_INPUT_PIN, PinState.HIGH);
    provider.setMockState(MockPin.DIGITAL_INPUT_PIN, PinState.LOW);

    // wait before continuing test
    Thread.sleep(50);

    // verify that the output pin state is low
    assertEquals(PinState.LOW, outputPin.getState());
  }
  public static void main(String[] args) {

    System.out.println("<--Pi4J--> GPIO Frequency Example ... started.");

    // create gpio controller
    final GpioController gpio = GpioFactory.getInstance();

    // provision gpio pin #01 as an output pin and turn on
    final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, PinState.LOW);

    // continuous loop
    while (true) {
      pin.setState(true);
      pin.setState(false);
    }

    // stop all GPIO activity/threads by shutting down the GPIO controller
    // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
    // gpio.shutdown();   <--- implement this method call if you wish to terminate the Pi4J GPIO
    // controller
  }
Example #12
0
  public static void main(String[] args) throws InterruptedException {
    System.out.println("works");
    GpioController gpio = GpioFactory.getInstance();
    GpioPinDigitalOutput pin1 =
        gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "MyLed", PinState.HIGH);
    pin1.setShutdownOptions(true, PinState.LOW);

    Thread.sleep(5000);
    System.out.println("pin low");
    pin1.low();

    Thread.sleep(5000);
    System.out.println("pin toggle");
    pin1.toggle();

    Thread.sleep(5000);
    System.out.println("pin pulse");
    pin1.pulse(1000, true);

    Thread.sleep(2000);
    System.out.println("pin blink");
    pin1.blink(500, 5000);

    Thread.sleep(2000);
    System.out.println("koniec");
    gpio.shutdown();
  }
Example #13
0
  public void addBit(boolean bit) throws InterruptedException {
    clear.setState(true);
    clock.setState(false);
    if (bit) {
      dataIn.setState(true);
    } else dataIn.setState(false);

    clock.setState(true); // clock in bit
    clock.setState(false); // turn off clock until next opersation
    dataIn.setState(false);
  }
Example #14
0
  /**
   * This method can be called to forcefully shutdown all GPIO controller monitoring, listening, and
   * task threads/executors.
   */
  @Override
  public synchronized void shutdown() {
    // prevent reentrant invocation
    if (isShutdown()) return;

    // shutdown all executor services
    //
    // NOTE: we are not permitted to access the shutdown() method of the individual
    // executor services, we must perform the shutdown with the factory
    GpioFactory.getExecutorServiceFactory().shutdown();

    // shutdown explicit configured GPIO pins
    for (GpioPin pin : pins) {

      // perform a shutdown on the GPIO provider for this pin
      if (!pin.getProvider().isShutdown()) {
        pin.getProvider().shutdown();
      }

      // perform the shutdown options if configured for the pin
      GpioPinShutdown shutdownOptions = pin.getShutdownOptions();
      if (shutdownOptions != null) {
        // get shutdown option configuration
        PinState state = shutdownOptions.getState();
        PinMode mode = shutdownOptions.getMode();
        PinPullResistance resistance = shutdownOptions.getPullResistor();
        Boolean unexport = shutdownOptions.getUnexport();

        // perform shutdown actions
        if ((state != null) && (pin instanceof GpioPinDigitalOutput)) {
          ((GpioPinDigitalOutput) pin).setState(state);
        }
        if (resistance != null) {
          pin.setPullResistance(resistance);
        }
        if (mode != null) {
          pin.setMode(mode);
        }
        if (unexport != null && unexport == Boolean.TRUE) {
          pin.unexport();
        }
      }
    }

    // set is shutdown tracking variable
    isshutdown = true;
  }
Example #15
0
  private void output(Exchange exchange, Object value) {

    //
    PinMode mode = pin.getMode();
    log.debug("Mode > " + mode + " for " + pin);

    // Check mode
    switch (mode) {
      case DIGITAL_OUTPUT:
        Boolean outputBoolean =
            exchange.getContext().getTypeConverter().convertTo(Boolean.class, value);
        ((GpioPinDigitalOutput) pin).setState(outputBoolean);
        break;

      case ANALOG_OUTPUT:
        Double outputDouble =
            exchange.getContext().getTypeConverter().convertTo(Double.class, value);
        ((GpioPinAnalogOutput) pin).setValue(outputDouble);
        break;

      case PWM_OUTPUT:
        Integer outputInt =
            exchange.getContext().getTypeConverter().convertTo(Integer.class, value);
        ((GpioPinPwmOutput) pin).setPwm(outputInt);

        break;

      case ANALOG_INPUT:
      case DIGITAL_INPUT:
        log.error("Cannot output with INPUT PinMode");
        break;

      default:
        log.error("Any PinMode found");
        break;
    }
  }
Example #16
0
 public void clear() throws InterruptedException {
   clear.setState(false);
   clear.setState(true);
   push();
 }
Example #17
0
 @Override
 public void invoke(GpioPin pin, PinState state) {
   if (targetPin != null) {
     targetPin.setState(targetPinState);
   }
 }
Example #18
0
  public static void main(String[] args) throws InterruptedException {

    // START SNIPPET: usage-create-controller-snippet
    // create gpio controller instance
    final GpioController gpio = GpioFactory.getInstance();
    // END SNIPPET: usage-create-controller-snippet

    // START SNIPPET: usage-provision-input-pin-snippet
    // provision gpio pin #02 as an input pin with its internal pull down resistor enabled
    // (configure pin edge to both rising and falling to get notified for HIGH and LOW state
    // changes)
    GpioPinDigitalInput myButton =
        gpio.provisionDigitalInputPin(
            RaspiPin.GPIO_02, // PIN NUMBER
            "MyButton", // PIN FRIENDLY NAME (optional)
            PinPullResistance.PULL_DOWN); // PIN RESISTANCE (optional)

    // END SNIPPET: usage-provision-input-pin-snippet
    // START SNIPPET: usage-provision-output-pin-snippet
    // provision gpio pins #04 as an output pin and make sure is is set to LOW at startup
    GpioPinDigitalOutput myLed =
        gpio.provisionDigitalOutputPin(
            RaspiPin.GPIO_04, // PIN NUMBER
            "My LED", // PIN FRIENDLY NAME (optional)
            PinState.LOW); // PIN STARTUP STATE (optional)
    // END SNIPPET: usage-provision-output-pin-snippet

    // START SNIPPET: usage-shutdown-pin-snippet
    // configure the pin shutdown behavior; these settings will be
    // automatically applied to the pin when the application is terminated
    // ensure that the LED is turned OFF when the application is shutdown
    myLed.setShutdownOptions(true, PinState.LOW, PinPullResistance.OFF);
    // END SNIPPET: usage-shutdown-pin-snippet

    // START SNIPPET: usage-control-pin-snippet
    // explicitly set a state on the pin object
    myLed.setState(PinState.HIGH);

    // use convenience wrapper method to set state on the pin object
    myLed.low();
    myLed.high();

    // use toggle method to apply inverse state on the pin object
    myLed.toggle();

    // use pulse method to set the pin to the HIGH state for
    // an explicit length of time in milliseconds
    myLed.pulse(1000);
    // END SNIPPET: usage-control-pin-snippet

    // START SNIPPET: usage-read-pin-snippet
    // get explicit state enumeration for the GPIO pin associated with the button
    PinState myButtonState = myButton.getState();

    // use convenience wrapper method to interrogate the button state
    boolean buttonPressed = myButton.isHigh();
    // END SNIPPET: usage-read-pin-snippet

    // START SNIPPET: usage-register-listener-snippet
    // create and register gpio pin listener
    myButton.addListener(new GpioUsageExampleListener());
    // END SNIPPET: usage-register-listener-snippet

    // START SNIPPET: usage-trigger-snippet
    // create a gpio synchronization trigger on the input pin
    // when the input state changes, also set LED controlling gpio pin to same state
    myButton.addTrigger(new GpioSyncStateTrigger(myLed));
    // END SNIPPET: usage-trigger-snippet

    // keep program running until user aborts (CTRL-C)
    while (true) {
      Thread.sleep(500);
    }

    // stop all GPIO activity/threads by shutting down the GPIO controller
    // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
    // gpio.shutdown();   <--- implement this method call if you wish to terminate the Pi4J GPIO
    // controller
  }
Example #19
0
  /** Process the message */
  @Override
  public void process(Exchange exchange) throws Exception {
    if (log.isTraceEnabled()) {
      log.trace(exchange.toString());
    }

    GPIOAction messageAction =
        exchange.getIn().getHeader(Pi4jConstants.CAMEL_RBPI_PIN_ACTION, action, GPIOAction.class);

    if (messageAction == null) {
      log.trace("No action pick up body");
      this.output(exchange, exchange.getIn().getBody());
    } else {
      log.trace("action= {} ", action);
      switch (messageAction) {
        case TOGGLE:
          if (pin.getMode() == PinMode.DIGITAL_OUTPUT) {
            ((GpioPinDigitalOutput) pin).toggle();
          }
          break;

        case LOW:
          if (pin.getMode() == PinMode.DIGITAL_OUTPUT) {
            ((GpioPinDigitalOutput) pin).low();
          }
          break;

        case HIGH:
          if (pin.getMode() == PinMode.DIGITAL_OUTPUT) {
            ((GpioPinDigitalOutput) pin).high();
          }
          break;

        case BLINK:
          if (pin.getMode() == PinMode.DIGITAL_OUTPUT) {

            pool.submit(
                new Runnable() {

                  @Override
                  public void run() {
                    try {
                      Thread.sleep(getEndpoint().getDelay());
                      ((GpioPinDigitalOutput) pin).toggle();
                      Thread.sleep(getEndpoint().getDuration());
                      ((GpioPinDigitalOutput) pin).toggle();
                    } catch (InterruptedException e) {
                      log.error("Thread interruption into BLINK sequence", e);
                    }
                  }
                });
          }

          break;

        default:
          log.error("Any action set found");
          break;
      }
    }
  }
Example #20
0
 private void turnLightOff() {
   lightPin.low();
   System.out.println(String.format("Light was turned off"));
 }
Example #21
0
 private void turnLightOn() {
   lightPin.high();
   System.out.println(String.format("Light was turned on"));
 }
Example #22
0
  /**
   * [ARGUMENT/OPTION "--pin (#)" | "-p (#)" ] This example program accepts an optional argument for
   * specifying the GPIO pin (by number) to use with this GPIO listener example. If no argument is
   * provided, then GPIO #1 will be used. -- EXAMPLE: "--pin 4" or "-p 0".
   *
   * @param args
   * @throws InterruptedException
   * @throws PlatformAlreadyAssignedException
   */
  public static void main(String[] args)
      throws InterruptedException, PlatformAlreadyAssignedException {

    // ####################################################################
    //
    // since we are not using the default Raspberry Pi platform, we should
    // explicitly assign the platform as the BananaPi platform.
    //
    // ####################################################################
    PlatformManager.setPlatform(Platform.BANANAPI);

    // create Pi4J console wrapper/helper
    // (This is a utility class to abstract some of the boilerplate code)
    final Console console = new Console();

    // print program title/header
    console.title("<-- The Pi4J Project -->", "GPIO Output Example");

    // allow for user to exit program using CTRL-C
    console.promptForExit();

    // create gpio controller
    final GpioController gpio = GpioFactory.getInstance();

    // ####################################################################
    //
    // When provisioning a pin, use the BananaPiPin class.
    //
    // ####################################################################

    // by default we will use gpio pin #01; however, if an argument
    // has been provided, then lookup the pin by address
    Pin pin =
        CommandArgumentParser.getPin(
            BananaPiPin.class, // pin provider class to obtain pin instance from
            BananaPiPin.GPIO_01, // default pin if no pin argument found
            args); // argument array to search in

    // provision gpio pin as an output pin and turn on
    final GpioPinDigitalOutput output =
        gpio.provisionDigitalOutputPin(pin, "My Output", PinState.HIGH);

    // set shutdown state for this pin: keep as output pin, set to low state
    output.setShutdownOptions(false, PinState.LOW);

    // create a pin listener to print out changes to the output gpio pin state
    output.addListener(
        new GpioPinListenerDigital() {
          @Override
          public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
            // display pin state on console
            console.println(
                " --> GPIO PIN STATE CHANGE: "
                    + event.getPin()
                    + " = "
                    + ConsoleColor.conditional(
                        event.getState().isHigh(), // conditional expression
                        ConsoleColor.GREEN, // positive conditional color
                        ConsoleColor.RED, // negative conditional color
                        event.getState())); // text to display
          }
        });

    // prompt user that we are ready
    console.println(" ... Successfully provisioned output pin: " + output.toString());
    console.emptyLine();
    console.box("The GPIO output pin states will cycle HIGH and LOW states now.");
    console.emptyLine();

    // notify user of current pin state
    console.println(
        "--> ["
            + output.toString()
            + "] state was provisioned with state = "
            + ConsoleColor.conditional(
                output.getState().isHigh(), // conditional expression
                ConsoleColor.GREEN, // positive conditional color
                ConsoleColor.RED, // negative conditional color
                output.getState())); // text to display

    // wait
    Thread.sleep(500);

    // --------------------------------------------------------------------------

    // tset gpio pin state to LOW
    console.emptyLine();
    console.println("Setting output pin state is set to LOW.");
    output.low(); // or ... output.setState(PinState.LOW);

    // wait
    Thread.sleep(500);

    // --------------------------------------------------------------------------

    // tset gpio pin state to HIGH
    console.emptyLine();
    console.println("Setting output pin state from LOW to HIGH.");
    output.setState(PinState.HIGH); // or ... output.high();

    // wait
    Thread.sleep(500);

    // --------------------------------------------------------------------------

    // toggle the current state of gpio pin (from HIGH to LOW)
    console.emptyLine();
    console.println("Toggling output pin state from HIGH to LOW.");
    output.toggle();

    // wait
    Thread.sleep(500);

    // --------------------------------------------------------------------------

    // pulse gpio pin state for 1 second HIGH and then return to LOW
    console.emptyLine();
    console.println("Pulsing output pin state HIGH for 1 second.");
    output.pulse(1000, true); // set second argument to 'true' use a blocking call
    Thread.sleep(50);

    // --------------------------------------------------------------------------

    // blink gpio pin state for 1 second between HIGH and LOW states
    console.emptyLine();
    console.println(
        "Blinking output pin state between HIGH and LOW for 3 seconds with a blink rate of 250ms.");
    Future future = output.blink(250, 3000);

    // --------------------------------------------------------------------------

    // wait for blinking to finish; we are notified in a future object
    while (!future.isDone()) {
      Thread.sleep(50);
    }

    // stop all GPIO activity/threads by shutting down the GPIO controller
    // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
    gpio.shutdown();
  }
Example #23
0
 public void push() throws InterruptedException {
   latch.setState(false);
   latch.setState(true);
   latch.setState(false);
 }