//Cosmic Pi Power supply open loop controller
//sets a value to the PSU and then increments it every n seconds.

//MAX1923 chip, with the following resistor values for feedback:
//R6 = 25k
//R5 = 200k
//R8 = 10k

//the old routine has been amended to fix the endian type (now correct)

//Default power up value is FF
//readback isn't supported and there's no external or integral temp feedback
//Pin 42 needs to be manually modified for the connection on V2 Alpha main boards

//Set the initial value
//reduce the value by 1 every 10 seconds
//voltage ramps slowly up to maximum (about 36V) and then rolls over
//note that 00 = DC/DC step up power off - i.e. no value output, input rail.
//The MAX1932 is powered from the 5V rail and accepts commands at 3.3V without problems.

//set up the pins to remap SPI by hand
const int SS_pin = 42; //tbc
const int SCK_pin = 44;
const int MISO_pin = 22;
const int MOSI_pin = 43;


//Define the sending variable
byte sendValue = 0xFF;   // Value we are going to send
byte returnValue = 0;  // Where we will store the value sent by the slave

void setup()
{
  digitalWrite(SS, HIGH);  // Start with SS high
  pinMode(SS_pin, OUTPUT);
  pinMode(SCK_pin, OUTPUT);
  pinMode(MISO_pin, INPUT); //this is the avalanche pin, not implemented yet
  pinMode(MOSI_pin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{

//write the value to console
//send the value
//decrement the variable and wait 10s before looping
  
Serial.println(sendValue, HEX);
returnValue = bitBang(sendValue); // Transmit data
sendValue = sendValue-1;

delay(10000);
}



byte bitBang(byte _send)  // This function is what bitbangs the data
{

  //reception isn't implemented in this version. 
  byte _receive = 0;
   digitalWrite(SS_pin, LOW);        // SS low 
  for(int i=0; i<8; i++)  // There are 8 bits in a byte
  {
    digitalWrite(MOSI_pin, bitRead(_send, 7-i));    // Set MOSI
    //delay(1);
    digitalWrite(SCK_pin, HIGH);                  // SCK high
    //bitWrite(_receive, i, digitalRead(MISO_pin)); // Capture MISO
    digitalWrite(SCK_pin, LOW);                   // SCK low
  //digitalWrite(MOSI_pin, LOW);    // Set MOSI
    
  }
   digitalWrite(SS_pin, HIGH);       // SS high again 
 
  //return _receive;        // Return the received data
}