Configures a pin to act either as input or output @param pin GPIO pin @param mode GPIO.INPUT, GPIO.INPUT_PULLUP, GPIO.INPUT_PULLDOWN, or GPIO.OUTPUT @see digitalRead @see digitalWrite @see releasePin @webref
(int pin, int mode)
| 335 | * @webref |
| 336 | */ |
| 337 | public static void pinMode(int pin, int mode) { |
| 338 | checkValidPin(pin); |
| 339 | |
| 340 | if (NativeInterface.isSimulated()) { |
| 341 | return; |
| 342 | } |
| 343 | |
| 344 | // export pin through sysfs |
| 345 | String fn = "/sys/class/gpio/export"; |
| 346 | int ret = NativeInterface.writeFile(fn, Integer.toString(pin)); |
| 347 | if (ret < 0) { |
| 348 | if (ret == -2) { // ENOENT |
| 349 | System.err.println("Make sure your kernel is compiled with GPIO_SYSFS enabled"); |
| 350 | } |
| 351 | if (ret == -22) { // EINVAL |
| 352 | System.err.println("GPIO pin " + pin + " does not seem to be available on your platform"); |
| 353 | } |
| 354 | if (ret != -16) { // EBUSY, returned when the pin is already exported |
| 355 | throw new RuntimeException(fn + ": " + NativeInterface.getError(ret)); |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | // set direction and default level for outputs |
| 360 | fn = String.format("/sys/class/gpio/gpio%d/direction", pin); |
| 361 | String out; |
| 362 | if (mode == INPUT) { |
| 363 | out = "in"; |
| 364 | |
| 365 | // attempt to disable any pre-set pullups on the Raspberry Pi |
| 366 | NativeInterface.raspbianGpioMemSetPinBias(pin, mode); |
| 367 | |
| 368 | } else if (mode == OUTPUT) { |
| 369 | if (values.get(pin)) { |
| 370 | out = "high"; |
| 371 | } else { |
| 372 | out = "low"; |
| 373 | } |
| 374 | } else if (mode == INPUT_PULLUP || mode == INPUT_PULLDOWN) { |
| 375 | out = "in"; |
| 376 | |
| 377 | // attempt to set pullups on the Raspberry Pi |
| 378 | ret = NativeInterface.raspbianGpioMemSetPinBias(pin, mode); |
| 379 | if (ret == -2) { // NOENT |
| 380 | System.err.println("Setting pullup or pulldown resistors is currently only supported on the Raspberry Pi running Raspbian. Continuing without."); |
| 381 | } else if (ret < 0) { |
| 382 | System.err.println("Error setting pullup or pulldown resistors: " + NativeInterface.getError(ret) + ". Continuing without."); |
| 383 | } |
| 384 | // currently this can't be done in a non-platform-specific way, see |
| 385 | // http://lists.infradead.org/pipermail/linux-rpi-kernel/2015-August/002146.html |
| 386 | |
| 387 | } else { |
| 388 | throw new IllegalArgumentException("Unknown mode"); |
| 389 | } |
| 390 | |
| 391 | // we need to give udev some time to change the file permissions behind our back |
| 392 | // retry for 500ms when writing to the file fails with -EACCES |
| 393 | long start = System.currentTimeMillis(); |
| 394 | do { |
no test coverage detected