// ADC0838.java by JWB, June 1, 2006
// based on ADC0831 and multi3 code
// this class could not be found by compilier..so it was redone as ADC_0838

//package stamp.peripheral.io.ADC;
import stamp.core.*;
import stamp.util.text.Format;

public class ADC0838 {
  // Pin Constants unique to chip
  private int enablePin;                  // ADC0838 enable pin #18
  private int dataPin;                    // ADC0838 data pin #14 in, #17 out
  private int clockPin;                   // ADC0838 clock pin #16
  private int clockIn;
  private  int muxbyte;
  private int readSize   = 9;                       // #Bits to Read on the ADC0838
  private int nBits = 5;                            // #bits to Send

  public ADC0838(int dataPin, int clockPin, int enablePin){

    // update protected variables
    this.dataPin   = dataPin;
    this.clockPin  = clockPin;
    this.enablePin = enablePin;
    //resolution = 256;                       // Range of the ADC0838

    CPU.writePin(enablePin, true); // set ready to trigger with high to low
    CPU.delay(100);
  }// end constructor: ADC0838

  /**
   * Read value from A to D chip.<p>
   * Multiple channels are available on the ADC0838
   * @param channel dummy value for ADC0831 to conform to base class
   * @return raw value from chip
   */
  public int read(int channel){

    CPU.writePin(clockPin, false);   // set clockpin low for + pulses
    //muxbyte = %11000 | ((channel &%001) << 2) |  ((channel & %110) >> 1);
    // %11000 = 24, %001 = 1, %110 = 6
    clockIn = 0;    muxbyte = 24 | ((channel & 1) << 2) |  ((channel & 6) >> 1);
    Format.printf(" muxbyte=%i",muxbyte);
    Format.printf(" dataPin=%i",dataPin);
    Format.printf(" clockPin=%i",clockPin);
    Format.printf(" enablePin=%i",enablePin);
    Format.printf(" readSize=%i",readSize);

    CPU.writePin(enablePin,false);     // trigger data xfer
    CPU.shiftOut(dataPin, clockPin, nBits, CPU.SHIFT_MSB, muxbyte <<11);
    //CPU.shiftOut(dataPin, clockPin, nBits, CPU.SHIFT_MSB, muxbyte <<8);
    clockIn = CPU.shiftIn(dataPin,clockPin,readSize,CPU.POST_CLOCK_MSB);
    CPU.writePin(enablePin,true);    //reset for next read

    clockIn = clockIn & 0x00FF;     // clear 9th bit, as per Jon Williams
    Format.printf(" clockIn=%i",clockIn);
    //clockIn = clockIn >>8;  // data byte must go to RHS after xfer
    //clockIn = CPU.shiftIn(dataPin,clockPin,readSize,CPU.PRE_CLOCK_MSB);


    CPU.delay(100);
    //lastRaw = clockIn;                               // raw is protected
    return clockIn;
  }// end method: read

}// end class: ADC0838 