// default constructor public PiFaceBase(byte spiAddress, SpiChannel spiChannel) throws IOException { // create Pi-Face GPIO provider gpioProvider = new PiFaceGpioProvider(spiAddress, spiChannel); // provision gpio input pins for the Pi-Face board inputPins = new GpioPinDigitalInput[] { gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_00), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_01), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_02), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_03), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_04), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_05), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_06), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_07) }; // provision gpio output pins for the Pi-Face board outputPins = new GpioPinDigitalOutput[] { gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_00), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_01), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_02), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_03), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_04), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_05), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_06), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_07) }; // create relay components for the first two output pins on the Pi-Face board relays = new Relay[] {new GpioRelayComponent(outputPins[0]), new GpioRelayComponent(outputPins[1])}; // create switch components for the first four input pins on the Pi-Face board switches = new Switch[] { new GpioSwitchComponent(inputPins[0], PinState.HIGH, PinState.LOW), new GpioSwitchComponent(inputPins[1], PinState.HIGH, PinState.LOW), new GpioSwitchComponent(inputPins[2], PinState.HIGH, PinState.LOW), new GpioSwitchComponent(inputPins[3], PinState.HIGH, PinState.LOW) }; // create LED components for the eight output pins on the Pi-Face board leds = new LED[] { new GpioLEDComponent(outputPins[0]), new GpioLEDComponent(outputPins[1]), new GpioLEDComponent(outputPins[2]), new GpioLEDComponent(outputPins[3]), new GpioLEDComponent(outputPins[4]), new GpioLEDComponent(outputPins[5]), new GpioLEDComponent(outputPins[6]), new GpioLEDComponent(outputPins[7]) }; }
public static void main(String[] args) throws InterruptedException { System.out.println("<--Pi4J--> GPIO Trigger Example ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // provision gpio pin #02 as an input pin with its internal pull down resistor enabled final GpioPinDigitalInput myButton = gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN); System.out.println(" ... complete the GPIO #02 circuit and see the triggers take effect."); // setup gpio pins #04, #05, #06 as an output pins and make sure they are all LOW at startup GpioPinDigitalOutput myLed[] = { gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "LED #1", PinState.LOW), gpio.provisionDigitalOutputPin(RaspiPin.GPIO_05, "LED #2", PinState.LOW), gpio.provisionDigitalOutputPin(RaspiPin.GPIO_06, "LED #3", PinState.LOW) }; // create a gpio control trigger on the input pin ; when the input goes HIGH, also set gpio pin // #04 to HIGH myButton.addTrigger(new GpioSetStateTrigger(PinState.HIGH, myLed[0], PinState.HIGH)); // create a gpio control trigger on the input pin ; when the input goes LOW, also set gpio pin // #04 to LOW myButton.addTrigger(new GpioSetStateTrigger(PinState.LOW, myLed[0], PinState.LOW)); // create a gpio synchronization trigger on the input pin; when the input changes, also set gpio // pin #05 to same state myButton.addTrigger(new GpioSyncStateTrigger(myLed[1])); // create a gpio pulse trigger on the input pin; when the input goes HIGH, also pulse gpio pin // #06 to the HIGH state for 1 second myButton.addTrigger(new GpioPulseStateTrigger(PinState.HIGH, myLed[2], 1000)); // create a gpio callback trigger on gpio pin#4; when #4 changes state, perform a callback // invocation on the user defined 'Callable' class instance myButton.addTrigger( new GpioCallbackTrigger( new Callable<Void>() { public Void call() throws Exception { System.out.println(" --> GPIO TRIGGER CALLBACK RECEIVED "); return null; } })); // keep program running until user aborts (CTRL-C) for (; ; ) { 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 }
private void provisionPins() { System.out.println(gpio.toString()); dataIn = gpio.provisionDigitalOutputPin( new PinImpl( "RaspberryPi GPIO Provider", pins[0], "Pin1", EnumSet.of(PinMode.DIGITAL_INPUT, PinMode.DIGITAL_OUTPUT), PinPullResistance.all()), "MyLED", PinState.LOW); outputEnable = gpio.provisionDigitalOutputPin( new PinImpl( "RaspberryPi GPIO Provider", pins[1], "Pin4", EnumSet.of(PinMode.DIGITAL_INPUT, PinMode.DIGITAL_OUTPUT), PinPullResistance.all()), "MyLED", PinState.LOW); latch = gpio.provisionDigitalOutputPin( new PinImpl( "RaspberryPi GPIO Provider", pins[2], "Pin5", EnumSet.of(PinMode.DIGITAL_INPUT, PinMode.DIGITAL_OUTPUT), PinPullResistance.all()), "MyLED", PinState.LOW); clear = gpio.provisionDigitalOutputPin( new PinImpl( "RaspberryPi GPIO Provider", pins[3], "Pin3", EnumSet.of(PinMode.DIGITAL_INPUT, PinMode.DIGITAL_OUTPUT), PinPullResistance.all()), "MyLED", PinState.HIGH); clock = gpio.provisionDigitalOutputPin( new PinImpl( "RaspberryPi GPIO Provider", pins[4], "Pin2", EnumSet.of(PinMode.DIGITAL_INPUT, PinMode.DIGITAL_OUTPUT), PinPullResistance.all()), "MyLED", PinState.LOW); }
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(); }
public static void main(String[] args) throws InterruptedException { System.out.println("<--Pi4J--> GPIO Cylon Example ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // provision gpio pin #01 as an output pin and turn on final GpioPinDigitalOutput[] pins = { gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, PinState.LOW), gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, PinState.LOW), gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, PinState.LOW), gpio.provisionDigitalOutputPin(RaspiPin.GPIO_03, PinState.LOW), gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, PinState.LOW), gpio.provisionDigitalOutputPin(RaspiPin.GPIO_05, PinState.LOW), gpio.provisionDigitalOutputPin(RaspiPin.GPIO_06, PinState.LOW), gpio.provisionDigitalOutputPin(RaspiPin.GPIO_07, PinState.LOW) }; System.out.println("--> GPIO state should be: ON"); // set shutdown options on all pins gpio.setShutdownOptions(true, PinState.LOW, pins); // infinite loop while (true) { for (int index = 0; index <= 6; index++) { pins[index].pulse(50); Thread.sleep(50); } for (int index = 6; index >= 0; index--) { pins[index].pulse(50); 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(); <--- implement this method call if you wish to terminate the Pi4J GPIO // controller }
@Before public void setup() { // create a mock gpio provider and controller provider = MockGpioFactory.getMockProvider(); gpio = MockGpioFactory.getInstance(); // provision pins for testing inputPin = gpio.provisionDigitalInputPin(MockPin.DIGITAL_INPUT_PIN, "digitalInputPin"); outputPin = gpio.provisionDigitalOutputPin(MockPin.DIGITAL_OUTPUT_PIN, "digitalOutputPin"); // create triggers triggerHigh = new GpioSetStateTrigger(PinState.HIGH, outputPin, PinState.HIGH); triggerLow = new GpioSetStateTrigger(PinState.LOW, outputPin, PinState.LOW); // add triggers to input pin inputPin.addTrigger(triggerHigh); inputPin.addTrigger(triggerLow); }
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 }
public GpioPinDigitalOutput getOutputPin(Integer pinNumber) { switch (pinNumber) { case 0: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00); case 1: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01); case 2: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02); case 3: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_03); case 4: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04); case 5: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_05); case 6: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_06); case 7: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_07); case 8: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_08); case 9: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_09); case 10: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_10); case 11: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_11); case 12: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_12); case 13: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_13); case 14: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_14); case 15: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_15); case 16: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_16); case 17: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_17); case 18: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_18); case 19: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_19); case 20: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_20); case 21: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_21); case 22: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_22); case 23: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_23); case 24: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_24); case 25: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_25); case 26: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_26); case 27: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_27); case 28: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_28); case 29: return gpio.provisionDigitalOutputPin(RaspiPin.GPIO_29); default: return null; } }
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 }
@Override public GpioPinDigitalOutput provisionDigitalOutputPin(Pin pin, PinState defaultState) { return delegate.provisionDigitalOutputPin(pin, defaultState); }
@Override public GpioPinDigitalOutput provisionDigitalOutputPin( GpioProvider provider, Pin pin, String name, PinState defaultState) { return delegate.provisionDigitalOutputPin(provider, pin, name, defaultState); }
@Override public GpioPinDigitalOutput provisionDigitalOutputPin(Pin pin) { return delegate.provisionDigitalOutputPin(pin); }
public static void main(String args[]) throws InterruptedException { System.out.println("<--Pi4J--> GPIO Listen Example ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // provision gpio pin #02 as an input pin with its internal pull down resistor enabled final GpioPinDigitalInput myButton = gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN); // create custom Olimex GPIO provider final OlimexAVRIOGpioProvider olimexProvider = new OlimexAVRIOGpioProvider(Serial.DEFAULT_COM_PORT); // provision gpio input pin #01 from Olimex final GpioPinDigitalInput myInput = gpio.provisionDigitalInputPin(olimexProvider, OlimexAVRIOPin.IN_01); // create gpio pin listener GpioPinListenerDigital listener = new GpioPinListenerDigital() { @Override public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) { // display pin state on console System.out.println( " --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState()); } }; // register gpio pin listener for each input pin myButton.addListener(listener); myInput.addListener(listener); // setup gpio pins #04, #05, #06 as an output pins and make sure they are all LOW at startup GpioPinDigitalOutput myRelays[] = { gpio.provisionDigitalOutputPin( olimexProvider, OlimexAVRIOPin.RELAY_01, "RELAY #1", PinState.LOW), gpio.provisionDigitalOutputPin( olimexProvider, OlimexAVRIOPin.RELAY_02, "RELAY #2", PinState.LOW), gpio.provisionDigitalOutputPin( olimexProvider, OlimexAVRIOPin.RELAY_03, "RELAY #3", PinState.LOW), gpio.provisionDigitalOutputPin( olimexProvider, OlimexAVRIOPin.RELAY_04, "RELAY #4", PinState.LOW) }; // create a gpio control trigger on the input pin ; when the input goes HIGH, also set gpio pin // #04 to HIGH myButton.addTrigger(new GpioSetStateTrigger(PinState.HIGH, myRelays[0], PinState.HIGH)); // create a gpio control trigger on the input pin ; when the input goes LOW, also set gpio pin // #04 to LOW myButton.addTrigger(new GpioSetStateTrigger(PinState.LOW, myRelays[0], PinState.LOW)); // create a gpio synchronization trigger on the input pin; when the input changes, also set gpio // pin #05 to same state myButton.addTrigger(new GpioSyncStateTrigger(myRelays[1])); // create a gpio synchronization trigger on the input pin; when the input changes, also set gpio // pin #05 to same state myButton.addTrigger(new GpioSyncStateTrigger(myRelays[2])); // create a gpio pulse trigger on the input pin; when the input goes HIGH, also pulse gpio pin // #06 to the HIGH state for 1 second myButton.addTrigger(new GpioPulseStateTrigger(PinState.HIGH, myRelays[3], 1000)); System.out.println( " ... complete the GPIO #02 circuit and see the listener feedback here in the console."); // keep program running until user aborts (CTRL-C) // or we reach 60 seconds for (int seconds = 0; seconds < 60; seconds++) { Thread.sleep(1000); } System.out.println(" ... exiting program."); // 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(); }
/* * * Essa classe foi criada a partir do exemplo em python do endereço abaixo * https://www.modmypi.com/blog/hc-sr04-ultrasonic-range-sensor-on-the-raspberry-pi * * */ public class HCSR04 { GpioController gpio = GpioFactory.getInstance(); // Configura os pinos GpioPinDigitalOutput trigger = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "trigger", PinState.LOW); GpioPinDigitalInput echo = gpio.provisionDigitalInputPin(RaspiPin.GPIO_05, "echo", PinPullResistance.PULL_DOWN); public long getDistancia() { System.out.println("Medição de distância em progresso..."); this.trigger.low(); System.out.println("Aguardando tempo do pino..."); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Iniciando a leitura System.out.println("Iniciando a leitura"); try { // Envia o sinal no pino Trigger // Coloca o trigger em HIGH por 10uS (8 ultrasound bursts at 40 kHz) this.trigger.high(); TimeUnit.MICROSECONDS.sleep(10); this.trigger.low(); // Escuta o pino de ECHO // O sensor emitirá uma onda sonora que ao encontrar um obstáculo // rebaterá de volta em direção ao módulo, sendo que o neste tempo // de emissão e recebimento do sinal o pino ECHO ficará em nivel alto. // Logo o calcula da distância pode ser feito de acordo com o tempo em // que o pino ECHO permaneceu em nível alto após o pino Trigger ter // sido colocado em nível alto. long inicio = 0; long fim = 0; while (this.echo.isLow()) { inicio = System.nanoTime(); } while (this.echo.isHigh()) { fim = System.nanoTime(); } // Calcula a diferença entre "fim" e "inicio" long duracao_pulso = fim - inicio; // Calcula distância long distancia = 17150 * duracao_pulso; // Round distancia = Math.round(distancia); System.out.println("Distancia: " + distancia); return distancia; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } }
public static void main(String args[]) throws InterruptedException, IOException { System.out.println("<--Pi4J--> PiFace (MCP23017) GPIO Example ... started."); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); // create custom PiFace GPIO provider final PiFaceGpioProvider gpioProvider = new PiFaceGpioProvider(PiFaceGpioProvider.DEFAULT_ADDRESS, SpiChannel.CS0); // provision gpio input pins from PiFaceGpioProvider GpioPinDigitalInput myInputs[] = { gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_00), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_01), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_02), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_03), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_04), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_05), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_06), gpio.provisionDigitalInputPin(gpioProvider, PiFacePin.INPUT_07) }; // create and register gpio pin listener gpio.addListener( new GpioPinListenerDigital() { @Override public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) { // display pin state on console System.out.println( " --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState()); } }, myInputs); // provision gpio output pins and make sure they are all LOW at startup GpioPinDigitalOutput myOutputs[] = { gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_00), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_01), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_02), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_03), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_04), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_05), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_06), gpio.provisionDigitalOutputPin(gpioProvider, PiFacePin.OUTPUT_07), }; // keep program running for 20 seconds for (int count = 0; count < 10; count++) { gpio.setState(true, myOutputs); Thread.sleep(1000); gpio.setState(false, myOutputs); Thread.sleep(1000); } // 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(); System.out.println("Exiting PiFaceGpioExample"); }
/** * [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(); }
@Override public GpioPinDigitalOutput provisionDigitalOutputPin(Pin pin, String name) { return delegate.provisionDigitalOutputPin(pin, name); }
@RestController public class motorController { GpioController gpio = GpioFactory.getInstance(); GpioPinDigitalOutput leftBackMotor = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "Motor Izquierda", PinState.LOW); GpioPinDigitalOutput rightBackMotor = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_05, "Motor Derecha", PinState.LOW); GpioPinDigitalOutput rightFrontMotor = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "Motor Derecha", PinState.LOW); GpioPinDigitalOutput leftFrontMotor = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_03, "Motor Derecha", PinState.LOW); @RequestMapping("/index") public String start() { return "app is running ok."; } @RequestMapping("/forward.htmlc") public String forward() throws InterruptedException { leftFrontMotor.high(); rightFrontMotor.high(); return "Moving forward..."; } @RequestMapping("/back.html") public String back() throws InterruptedException { leftBackMotor.high(); rightBackMotor.high(); return "Moving backwards..."; } @RequestMapping("/right.html") public String right() throws InterruptedException { leftFrontMotor.toggle(); rightFrontMotor.toggle(); return "Moving right..."; } @RequestMapping("/left.html") public String left() throws InterruptedException { leftFrontMotor.toggle(); rightFrontMotor.toggle(); return "Moving left..."; } @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"; } }
public class SocketServer { private ServerSocket serverSocket; public static final int SERVERPORT = 6000; // ================ // Commands // ================ private static String LIGHT_ON = "light_on"; private static String LIGHT_OFF = "light_off"; private static String DOOR_OPEN = "door_open"; private static String DOOR_CLOSE = "door_close"; // ================ // GPIO block // ================ final GpioController gpio = GpioFactory.getInstance(); final GpioPinDigitalOutput lightPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "MyLED", PinState.LOW); final GpioPinDigitalInput myButton = gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN); Socket socket = null; GpioCallbackTrigger doorRingTrigger; public SocketServer() { try { initializeSoftPWM(); System.out.println("Waiting for connect ..."); createSocket(); System.out.println("Device is connected"); createDoorBell(); createCommandReader(); // Wait until user stops the application Scanner scanIn = new Scanner(System.in); String nextLine = ""; while (true) { nextLine = scanIn.nextLine(); if (nextLine.equals("!exit")) { System.exit(0); } ; } } catch (SocketException e) { System.out.println(String.format("Socket connect is broken: \n %s", e.getMessage())); System.exit(0); } catch (IOException e) { System.out.println(String.format("Something wrong: \n %s", e.getMessage())); System.exit(0); } } private void createSocket() throws IOException, SocketException { serverSocket = new ServerSocket(SERVERPORT); socket = serverSocket.accept(); socket.setKeepAlive(true); } private void initializeSoftPWM() { Gpio.wiringPiSetup(); SoftPwm.softPwmCreate(26, 0, 100); } private void createCommandReader() { new Thread(new CommandReader()).start(); } private class CommandReader implements Runnable { public void run() { try { BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); while (true) { String read = input.readLine(); if (read != null && !read.isEmpty()) { System.out.println(String.format("Message: '%s' was received", read)); reactToCommand(read); } } } catch (IOException e) { System.out.println(String.format("Cannot create input stream: \n %s", e.getMessage())); } } } private void createDoorBell() { new Thread(new DoorRingListener()).start(); } private class DoorRingListener implements Runnable { public void run() { try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); doorRingTrigger = creareDoorRingTrigger(out); myButton.addTrigger(doorRingTrigger); } catch (IOException e) { System.out.println(String.format("Cannot create output stream: \n %s", e.getMessage())); } } } private GpioCallbackTrigger creareDoorRingTrigger(final PrintWriter out) { return new GpioCallbackTrigger( new Callable<Void>() { public Void call() throws Exception { myButton.removeAllTriggers(); System.out.println("Someone comes to home"); sendNotificationToClient(out); try { Thread.sleep(500); } catch (InterruptedException e) { } myButton.addTrigger(doorRingTrigger); return null; } }); } private void sendNotificationToClient(PrintWriter out) { out.println("Someone comes to home"); out.flush(); } private void reactToCommand(String read) { if (read.equalsIgnoreCase(LIGHT_ON)) { turnLightOn(); } else if (read.equalsIgnoreCase(LIGHT_OFF)) { turnLightOff(); } else if (read.equalsIgnoreCase(DOOR_OPEN)) { openDoor(); } else if (read.equalsIgnoreCase(DOOR_CLOSE)) { closeDoor(); } } private void closeDoor() { SoftPwm.softPwmWrite(26, 5); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } SoftPwm.softPwmWrite(26, 00); } private void openDoor() { SoftPwm.softPwmWrite(26, 45); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } SoftPwm.softPwmWrite(26, 00); } private void turnLightOff() { lightPin.low(); System.out.println(String.format("Light was turned off")); } private void turnLightOn() { lightPin.high(); System.out.println(String.format("Light was turned on")); } public static void main(String[] args) { new SocketServer(); } }