/*
 ADS1256 ADC is used for this test. Command for write 
 and read is taken from the datasheet.
*/

#include "SPI.h"

#define CS_PIN        9 // P1_8

// address of register to read and write
const int reg_to_test = 0x03;
uint8_t readVal = 0;
uint8_t writeVal = 0;

// read one register value
uint8_t ADC_read_register(uint8_t registerAddress)
{
  SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE1));
  digitalWrite(CS_PIN, LOW);            // CS must stay LOW during the entire sequence
  SPI.transfer(0x10 | registerAddress); // 0x10 = 0001000 = RREG - OR together the two numbers (command + address)
  SPI.transfer(0x00);                   // 2nd empty command byte to read one byte
  delayMicroseconds(5);                 // see t6 in the datasheet
  uint8_t readVal = SPI.transfer(0xFF); // read out the register value
  digitalWrite(CS_PIN, HIGH);
  SPI.endTransaction();
  return readVal;
}

// write one register value
void ADC_write_register(uint8_t registerAddress, uint8_t registerValueToWrite)
{
  SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE1));
  digitalWrite(CS_PIN, LOW);            // CS must stay LOW during the entire sequence
  delayMicroseconds(5);                 // see t6 in the datasheet
  SPI.transfer(0x50 | registerAddress); // 0x50 = 01010000 = WREG
  SPI.transfer(0x00);                   // 2nd empty command byte to write one byte
  SPI.transfer(registerValueToWrite);   // pass the value to the register
  digitalWrite(CS_PIN, HIGH);
  SPI.endTransaction();
}

// ----------------------------------------- //
void setup() 
{
  Serial.begin(9600);
  Serial.println("Start spi test");

  // init chip select pin
  pinMode(CS_PIN, OUTPUT);
  digitalWrite(CS_PIN, HIGH);

  // init spi
  SPI.begin();
  delay(100);

  // read initial register value
  Serial.print("Initial register value: 0x");
  Serial.println(ADC_read_register(reg_to_test), HEX);
}

void loop() 
{
  // write new reg value
  ADC_write_register(reg_to_test, writeVal);
  Serial.print("Write val: 0x");
  Serial.println(writeVal, HEX);
  
  // read updated reg value
  readVal = ADC_read_register(reg_to_test);
  Serial.print("Read val: 0x");
  Serial.println(readVal, HEX);

  // increase write value
  writeVal++;
  Serial.println("-------------");

  // wait
  delay(2000);
}
