//
//  LTC2439.cpp
//  libLTC
//
//  Created by Tim THUREL on 04/03/2020.
//  Copyright © 2020 Tim THUREL. All rights reserved.
//

#include "LTC2439.h"



#ifdef DEBUG
    
#endif


LTC::LTC(int CSpin){
    SPI.begin();
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
    SPI.setClockDivider(SPI_CLOCK_DIV16);
    
    pinMode(CSpin, OUTPUT);
    pinMode(CSpin, HIGH);
    
    pinConv = 12;
    selectPin = CSpin;
    SPI.end();
}

LTC::LTC(int CSpin, int SDOpin){
    SPI.begin();
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
    SPI.setClockDivider(SPI_CLOCK_DIV16);
    
    pinMode(CSpin, OUTPUT);
    pinMode(CSpin, HIGH);
    
    pinConv = SDOpin;
    selectPin = CSpin;
    SPI.end();
}
LTC::LTC(int CSpin, int SDOpin, int F0pin){
    SPI.begin();
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
    SPI.setClockDivider(SPI_CLOCK_DIV16);
    
    pinMode(CSpin, OUTPUT);
    pinMode(CSpin, HIGH);

    pinMode(F0pin, OUTPUT);
    pinMode(F0pin, LOW);
    
    pinConv = SDOpin;
    selectPin = CSpin;
    pinF0 = F0pin;
    SPI.end();
}

long LTC::readValue(int channel){

    //envoie de la commande

    digitalWrite(selectPin, LOW);
    
    pinMode(pinConv, INPUT);
    
    while(digitalRead(pinConv) == 1){}

    SPI.begin();
    SPI.beginTransaction(SPISettings(500000, MSBFIRST,SPI_MODE0));
    
    SPI.transfer(0b10110000 | tableChanel[channel]);
    digitalWrite(selectPin, HIGH);

    SPI.end();

    
    #ifndef ARDUINO
    delay(5);
    #endif
    // recuperation des data
    digitalWrite(selectPin, LOW);
    
    pinMode(pinConv, INPUT);
    
    while(digitalRead(pinConv) == 1){}

    SPI.begin();
    SPI.beginTransaction(SPISettings(500000, MSBFIRST,SPI_MODE0));

    int8_t bitsleft = 19;
    long result = 0;
    
    while(bitsleft > 0) {
           result <<= 8;
           result |= SPI.transfer(0);
           bitsleft -= 8;
       }

    SPI.end();

    digitalWrite(selectPin,HIGH);
    result >>= -bitsleft;
    int pos = (result & 0b10000000000000000)>> 16;
    unsigned long mask = 0b1111111111111111;
    result &= mask;
    
    if(!pos && result != 0){
        result = result | (~mask);
    }
    return result;
}


#ifdef ARDUINO

//void LTC::startTimer(int frequency)
//{
//    cli();//stop interrupts
//    
//    TCCR2A = 0;// set entire TCCR2A register to 0
//    TCCR2B = 0;// same for TCCR2B
//    TCNT2  = 0;//initialize counter value to 0
//
//    OCR2A = (1/frequency)*5*10^5;
//    // turn on CTC mode
//    TCCR2A |= (1 << WGM21);
//    // Set CS21 bit for 8 prescaler
//    TCCR2B |= (1 << CS21);   
//    // enable timer compare interrupt
//    TIMSK2 |= (1 << OCIE2A);
//
//    sei();//allow interrupts
//}
//
//ISR(TIMER2_COMPA_vect){
//    toggle = !toggle;
//    digitalWrite(pinF0,toggle);
//
//}

#endif








