#include #include "SPI.h" uchar SPI_CS = 0; int SPIInit(){ UCA0CTL1 = UCSWRST; // setup A0 for SPI UCA0CTL0 = UCMSB | UCMST | (0x10 << 1) | UCSYNC; UCA0CTL1 |= UCSSEL_2; UCA0BR1 = 0; UCA0BR0 = 16; // 1 MHz // config port //set SEL to USCI (0b01); MOSI (pin 1), MISO (pin 2), CLK (pin 4) P1SEL |= BIT1 | BIT2 | BIT4; P1SEL2 |= BIT1 | BIT2 | BIT4; UCA0CTL1 &= ~UCSWRST; // enable interrupts // IE2 |= UCA0TXIE; // IFG2 &= ~UCA0TXIFG; // set initial values for vars SPI_packetC = 0; SPI_CS = 0; __enable_interrupt(); return 0; } //TODO: add clock freqency configuration /* * do some configuration before sending the data. * * @arg uchar cs: the bit of port 1 connected to the chip select pin of target device * @arg enum SPI_Mode: the SPI modus (clock pase and polarity) * @arg enum SPI_clock: the clock freqency */ void SPIInitSend(uchar cs, enum SPI_Mode mode, enum SPI_Clock clk){ //TODO: add a clock as powerefficent delay while(SPI_CS != 0); // wait for last transmit to be done // set clock frequency UCA0BR0 = clk; // set SPI mode UCA0CTL0 &= 0x3F; // set mode bits to 0 UCA0CTL0 |= mode; // save chip select SPI_CS = cs; } //TODO: make it asyncronily with interupt. /* * Send the packet stored in SPI_packet. it start from SPI_packetC to the last byte */ void SPISend(){ P1OUT &= ~SPI_CS; // select slave while(SPI_packetC < 5){ // send one byte UCA0TXBUF = SPI_packet[SPI_packetC]; //TODO: fix the delay! it's to short with low data speeds if(UCA0BR0 > 4) // if de frequency lower than 4 MHz do a manual delay. this is a workaround for the to short delay // this works down to 1 MHz __delay_cycles(129); else while(UCB0STAT & UCBUSY); // wait for SPI TX/RX to finish // save recieved data SPI_packet[SPI_packetC] = UCA0RXBUF; // increase counter for next byte SPI_packetC++; } SPI_packetC = 0; // recet counter P1OUT |= SPI_CS; // deselect slave SPI_CS = 0; }