/// File:   SPIbus.h
/// Author: jfriederich
/// Created on February 3, 2015, 2:04 PM
/// @file SPIbus.h
/// @brief communicate over SPI
#ifndef SPIBUS_H
#define	SPIBUS_H
#include "cwgsys.h"
#include "pic24.h"

//con1 == SPIxCON1, con2 == SPIxCON2, stat == SPIxSTAT
typedef struct { 
    uint16_t con1; 
    uint16_t con2; 
    uint16_t stat;
    uint16_t brgl;
} spi1_configuration_t;

typedef enum {
    MODE_SLOW=0,
    MODE_FAST,
    MODE_RTC
}spi_mode_id;


/// @brief Set slower SPI speed
void spiSlow(void);
/// @brief Set faster SPI speed
void spiFast(void);
/// @brief Turn off RTC's CS line
void spiDeselectRTC(void);
/// @brief Change modes to talk to RTC, enable its CS
void spiSelectRTC(void);
/// @brief Turn off SDcard's CS line
void spiDeselectSD(void);
/// @brief Change modes to talk to SDcard, enable its CS
int spiSelectSD(void);
/// @brief wait .5 sec for ready signal from SDcard
/// @return 1:received 0xFF, 0: timed out
int spiWaitReady(void);
/// @brief send and receive one byte over SPI
/// @param dat Byte to send
/// @return Byte received
BYTE spiExchange(BYTE dat);
/// @brief send several bytes, ignore received bytes
/// @param buff data to transmit
/// @param cnt number of bytes to send
void spiXmitMulti(const BYTE* buff, UINT cnt);
/// @brief receive several bytes, transmits 0xFFs
/// @param [out] buff Buffer to fill with data
/// @param cnt number of bytes to get
void spiRcvrMulti(BYTE* buff, UINT cnt);

void spi1_close(void);
bool spi1_master_open(spi_mode_id spiUniqueConfiguration);

#endif	/// SPIBUS_H 