#include <htc.h>
#include <pic16f690.h>
void initTMR0 (void);
void initUARTsend (void);
void initSPI (void);
signed int SPI_receive();
void UART_send(signed int temp_out);
void main()
{
initTMR0(); //TMR0 init
initUARTsend(); // UART init
initSPI();
signed int temp;
temp=0;
PORTC=0; // PORTC reset
while(1)
{
temp = SPI_receive();
__delay_ms(100);
UART_send(temp);
}
}
void initTMR0(void)
{
OPTION_REGbits.PS0=1; //Prescaler is divide by 256
OPTION_REGbits.PS1=1;
OPTION_REGbits.PS2=1;
OPTION_REGbits.PSA=0; //Timer Clock Source is from Prescaler
OPTION_REGbits.T0CS=0;//Prescaler gets clock from FCPU (1MHz)
INTCONbits.T0IE=1; //Enable TIMER0 Interrupt
INTCONbits.T0IF=0;
INTCONbits.PEIE=1; //Enable Peripheral Interrupt
INTCONbits.GIE=1; //Enable INTs globally
}
void initUARTsend(void)
{
SPBRG = 25; //Fosch 4Mhz -> baudrate 2400
TXSTAbits.BRGH = 0; //Sets Low Baud Rate
TXSTAbits.SYNC = 0; //Sets Asynchronous mode
RCSTAbits.SPEN = 1; //Enables EUSART
TXSTAbits.TXEN = 1; //Enables the EUSART transmiter
}
void initSPI(void)
{
TRISCbits.TRISC6=0; //CS SPI output
TRISCbits.TRISC7=0; //SDO SPI out
TRISBbits.TRISB6=0; //SCK out
TRISBbits.TRISB4=1; //SDI SPI IN
SSPCONbits.SSPEN = 1; //= Enables serial port and configures SCK, SDO and SDI as serial port pins
SSPCONbits.CKP = 1; //Idle state for clock is a low level (Microwire alternate)
SSPCONbits.SSPM = 0; //SPI Master mode, clock = FOSC/4
SSPSTATbits.SMP = 0; // Input data sampled at middle of data output time
SSPSTATbits.CKE = 1; //data transfer on rising edge clk
}
signed int SPI_receive()
{
signed int temp_out_msb;
signed int temp_out_lsb;
signed int temp_out;
temp_out = 0;
PORTCbits.RC6 = 0; //CS laag, initieer communicatie
__delay_ms(10);
SSPBUF = 0; //dummy to start clk
//First 8 bits
while(!PIR1bits.SSPIF) //wait for receive complete
temp_out_msb = SSPBUF;
PIR1bits.SSPIF = 0;
//last 6 bits
SSPBUF = 0; // write dummy data again to initiate second receive
while(!PIR1bits.SSPIF) //wait for receive complete
temp_out_lsb = SSPBUF;
PIR1bits.SSPIF = 0;
PORTCbits.RC6 = 1; //CS high, stop SPI
temp_out = ((temp_out_msb << 8 ) | (temp_out_lsb )); //shift bits to find temp
return temp_out;
}
void UART_send(signed int temp_out)
{
while(!TRMT);
TXREG = temp_out; //Transmit the binary number 1x per se
}