savageautomate

Raspberry Pi - Java GPIO Frequency Test (java.nio)

Jan 9th, 2013
212
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.io.File;
  2. import java.io.FileWriter;
  3. import java.nio.file.*;
  4.  
  5.  
  6. public class GpioNioTest
  7. {
  8.     static String GpioChannel = "18";
  9.    
  10.     /**
  11.      * @param args the command line arguments
  12.      */
  13.     public static void main(String[] args) {
  14.         try {
  15.            
  16.            
  17.             /*** Init GPIO port for output ***/
  18.             // Open file handles to GPIO port unexport and export controls
  19.             FileWriter unexportFile = new FileWriter("/sys/class/gpio/unexport");
  20.             FileWriter exportFile = new FileWriter("/sys/class/gpio/export");
  21.  
  22.             // Reset the port
  23.             File exportFileCheck = new File("/sys/class/gpio/gpio"+ GpioChannel);
  24.             if (exportFileCheck.exists()) {
  25.                 unexportFile.write(GpioChannel);
  26.                 unexportFile.flush();
  27.             }
  28.        
  29.             // Set the port for use
  30.             exportFile.write(GpioChannel);  
  31.             exportFile.flush();
  32.  
  33.             // Open file handle to port input/output control
  34.             FileWriter directionFile = new FileWriter("/sys/class/gpio/gpio" + GpioChannel + "/direction");
  35.        
  36.             // Set port for output
  37.             directionFile.write("out");
  38.             directionFile.flush();
  39.                            
  40.             /*** Send commands to GPIO port ***/
  41.             FileSystem fs = FileSystems.getDefault();
  42.             Path commandChannel = fs.getPath("/sys/class/gpio/gpio" + GpioChannel + "/value");
  43.             byte[] OFF = "0".getBytes();
  44.             byte[] ON = "1".getBytes();
  45.            
  46.             // Loop forever
  47.             while (true) {
  48.                
  49.                 // Set GPIO port ON
  50.                 Files.write(commandChannel, ON);
  51.            
  52.                 // Set GPIO port OFF
  53.                 Files.write(commandChannel, OFF);
  54.             }
  55.  
  56.         } catch (Exception exception) {
  57.             exception.printStackTrace();
  58.         }
  59.     }
  60. }
RAW Paste Data