//definice HW: funkce pro inicializaci portu, kde jsou pripojeny
//chip selecty
//#define STPM_CS_INIT()	{LATB|=0b00001111;TRISB&=0b11110000;}

//vypnuti vsech CS
//#define STPM_CS_OFF()	{LATB|=0b00001111;}

//zapnuti CS STPM10 cislo x (x je 0 .. STPM_NUMBER-1)
//#define STPM_CS_ON(x)	{LATB&=~(1<<x);}

#include <p18cxxx.h>
#include <delays.h>
#include <usart.h>
#include <stdio.h>
#include <spi.h>

#include "stpm18spi.h"

#define STPM_SYNC	LATCbits.LATC2
#define STPM_INIT_IODIR()	{TRISCbits.TRISC2=0;TRISCbits.TRISC3=0;TRISCbits.TRISC4=1;TRISCbits.TRISC5=1;}
#define STPM_IODIR_READ()	{TRISCbits.TRISC5=1;}
#define STPM_IODIR_WRITE()	{TRISCbits.TRISC5=0;}

//definice HW: pripojeni knihovny pro komunikaci SPI
void initSPI() {
	STPM_INIT_IODIR();
	STPM_SYNC = 1;
	OpenSPI1(SPI_FOSC_64, MODE_11, SMPMID);
}

//definice HW: posle SYNC a zapne CS
void sendSync(unsigned char stpmId) {
	STPM_IODIR_READ();
	STPM_SYNC = 0;
	Delay10TCYx(5);
	STPM_CS_ON(stpmId);
	Delay10TCYx(1);
	STPM_SYNC = 1;
}

//definice HW: vycte blok dat z STPM
void readSTPM(unsigned char stpmId, unsigned char bytes, unsigned char * block) {
	unsigned char *pozice = block;
	unsigned char pocet = bytes;

	sendSync(stpmId);

	while (pocet) {
		//cist jeden byte z SPI
		(*pozice) = ReadSPI1();
		pozice++;
		pocet--;
	}

	STPM_CS_OFF();
}

//definice HW: zapis bitu na STPM
void writeSTPMBit(unsigned char stpmId, unsigned char bitId, unsigned char value) {
	STPM_SYNC = 1;
	Delay10TCYx(1);
	STPM_CS_ON(stpmId);
	Delay10TCYx(1);
	STPM_SYNC = 0;
	STPM_IODIR_WRITE();
	WriteSPI1((bitId<<1)|(value?128:0));
	STPM_IODIR_READ();
	STPM_SYNC = 1;
	STPM_CS_OFF();
	Delay10TCYx(1);
}

