Example #1
0
  /*
   * Read a single pair of (X,Y) values from the ADXL202EVB board.
   * TODO: Better return value, or declare as throwing exception for errs
   */
  public static double[] chipRead() {
    double[] retval = {0.0, 0.0};
    byte[] rawBuf = {0, 0, 0, 0};
    int[] vals = {0, 0};

    try {
      // Read is triggered by sending 'G' to board
      outputStream.write('G');

      // Wait for all 4 result bytes to arrive
      // TODO: Finite wait w/error return if data never arrives
      while (inputStream.available() < 4) {
        Thread.sleep(1);
      }

      inputStream.read(rawBuf, 0, 4);

      // Convert from raw bytes to 16-bit signed integers, carefully
      Byte bTmp = new Byte(rawBuf[0]);
      vals[0] = bTmp.intValue() * 256;
      bTmp = new Byte(rawBuf[1]);
      vals[0] += bTmp.intValue();

      bTmp = new Byte(rawBuf[2]);
      vals[1] = bTmp.intValue() * 256;
      bTmp = new Byte(rawBuf[3]);
      vals[1] += bTmp.intValue();

      // See ADXL202EVB specs for details on conversion
      retval[0] = (((vals[0] / 100.0) - 50.0) / 12.5);
      retval[1] = (((vals[1] / 100.0) - 50.0) / 12.5);

      System.out.println("X: " + retval[0] + " Y: " + retval[1]);

    } catch (Exception ioe) {
      System.out.println("Error on data transmission");
    }
    return (retval);
  }
  /**
   * Convert a byte array to a hex string
   *
   * @param bytes byte array to convert to a hex string
   * @return return a String in hex representing the byte array
   */
  public String toHexString(byte[] bytes) {
    StringBuffer result = new StringBuffer("0x");

    for (int i = 0; i < bytes.length; i++) {
      Byte aByte = new Byte(bytes[i]);
      Integer anInt = new Integer(aByte.intValue());
      String hexVal = Integer.toHexString(anInt.intValue());

      if (hexVal.length() > SIZE) hexVal = hexVal.substring(hexVal.length() - SIZE);

      result.append(
          (SIZE > hexVal.length() ? ZEROS.substring(0, SIZE - hexVal.length()) : "") + hexVal);
    }
    return (result.toString());
  }