#include <msp430x16x.h>
#include "main.h"
#include "spi.h"
/* Initialize and enable the SPI module */
void spi_initialize()
{
P5SEL = 0x00E; // Setup P5 for SPI mode
P5OUT |= 0x010; // Setup P5.4 as the SS signal, active
// low. So, initialize it high.
P5DIR |= 0x010; // Set up P5.4 as an output
U1CTL = (CHAR | SYNC | MM | SWRST); // 8-bit, SPI, Master
U1TCTL = (SSEL1 | STC | CKPH); // Normal polarity, 3-wire
U1BR0 = 0x002; // SPICLK = SMCLK/2 (2=Minimum divisor)
U1BR1 = 0x000;
U1MCTL = 0x000;
ME2 |= USPIE1; // Module enable
U1CTL &= ~SWRST; // SPI enable
}
/* Set the baud-rate divisor. The correct value is computed by dividing
the clock rate by the desired baud rate. The minimum divisor allowed
is 2. */
void spi_set_divisor(unsigned int divisor)
{
U1CTL |= SWRST; // Temporarily disable the SPI module
U1BR1 = divisor >> 8;
U1BR0 = divisor;
U1CTL &= ~SWRST; // Re-enable SPI
}
/* Assert the CS signal, active low (CS=0) */
void spi_cs_assert()
{
// Pin 5.4, Pin 48
P5OUT &= ~0x010;
}
/* Deassert the CS signal (CS=1) */
void spi_cs_deassert()
{
// Pin 5.4, Pin 48
P5OUT |= 0x010;
}
/* Send a single byte over the SPI port */
void spi_send_byte(unsigned char input)
{
IFG2 &= ~URXIFG1;
/* Send the byte */
TXBUF1 = input;
/* Wait for the byte to be sent */
while ((IFG2 & URXIFG1) == 0) { }
}
/* Receive a byte. Output an 0xFF (the bus idles high) to receive the byte */
unsigned char spi_rcv_byte()
{
unsigned char tmp;
IFG2 &= ~URXIFG1;
/* Send the byte */
TXBUF1 = 0xFF;
/* Wait for the byte to be received */
while ((IFG2 & URXIFG1) == 0) { }
tmp = U1RXBUF;
return (tmp);
}
/* Disable the SPI module. This function assumes the module had
* already been initialized. */
void spi_disable()
{
/* Put the SPI module in reset mode */
U1CTL |= SWRST;
/* Disable the USART module */
ME2 &= ~USPIE1;
}
void spi_enable()
{
/* Enable the USART module */
ME1 |= USPIE1;
/* Take the SPI module out of reset mode */
U1CTL &= ~SWRST;
}
