Interactive SPI

The SPI protocol can be tricky enough to get working especially if you are unsure of the MCU you are using and/or the peripheral.  Logic analyzers can help but can also be expensive.  With the help of the following Energia MSP430G2553 code and a dumb terminal serial application program (on your PC) you can interact live with an SPI peripheral and hopefully come to grips with its operation.

The peripheral can be wired as follows:
LaunchPads-MSP430G2-—-Pins-Maps-13-42

Launchpad                   Peripheral
MOSI------------------------MOSI
MISO------------------------MISO
P1_0------------------------SS (slave select or CE)
GND-------------------------GND
Vcc-------------------------Vcc

Check the peripheral power requirements first and don’t connect a 5V peripheral directly to a 3.3V MSP430

The program presents the user with a simple menu:

Please select from one of the following:
0: SS Low
1: SS High
2: Write byte
3: Read byte

If you choose 0 or 1, SS is raised or lowered as appropriate and the menu recycles. If you choose 2 you see this (I entered the value ‘a9’ (not case sensitive))

Please select from one of the following:
0: SS Low
1: SS High
2: Write byte
3: Read byte
Enter a 2 character hex value: a9
Out : A9
In : 0

If you choose 3 you will see something like this:

Please select from one of the following:
0: SS Low
1: SS High
2: Write byte
3: Read byte
In : 0

The code is shown below. You will probably need to check out which SPI modes and byte ordering suit you. Also, the SPI interface is running at the very low speed of 125kHz. This was deliberate as it reduces the risk of data errors on shaky test leads and may help debugging. You can of course change this. The divider is divided into 16MHz to give an SPI data rate. This is very definitely version 0.1 and changes are likely in the future when I do some real testing.

/*
 * SPI protocol tester using the MSP430G2553 G2 Launchpad
 * This program allows you manage an SPI bus,write and read data
 * using a serial dumb terminal application
 * The program makes use of the Energia Serial and SPI libraries
 * Serial interface : 9600,n,8,1
 * SPI library reference : http://energia.nu/reference/spi/
 * 
 */
#include <SPI.h>

// Will use P1_0 as SS pin as there is a handy LED there on the launchpad
#define SS_Pin  P1_0


int getUserCommand();
int getInteger(String Prompt);
void setup() {
  // put your setup code here, to run once:
  // Default SPI configuration : feel free to change!
  // Set up the SS Pin and make it HIGH initially (low wakes up a slave)
  pinMode(SS_Pin,OUTPUT);  
  digitalWrite(SS_Pin,HIGH);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0); // can choose modes 0,1,2,3
  SPI.setBitOrder(MSBFIRST);  // can be MSBFIRST or LSBFIRST
  SPI.setClockDivider(128);   // assuming a system clock of 16MHz this gives an 
                              // SPI speed of 125kHz - deliberately slow to be more forgiving and
                              // to make signals easier to see with a scope of logic analyser
  // Serial communications to host setup
  Serial.begin(9600);
}
int TXByte,RXByte;
void loop() {
  
  // put your main code here, to run repeatedly: 
  switch (getUserCommand())
  {
    case 0 : {
      // Command 0 : drop SS pin down
      digitalWrite(SS_Pin,LOW);    
      break;
    }
    case 1 : {
      // Command 1 : raise SS pin up
      digitalWrite(SS_Pin,HIGH);
      break;
    }
    case 2 : {
      // Command 2 : send a byte
      TXByte = getInteger("Enter a value to transmit: ");
      RXByte = SPI.transfer(TXByte);
      Serial.print("Out : ");
      Serial.println(TXByte,HEX);
      Serial.print("In : ");
      Serial.println(RXByte,HEX);
      break;
    }
    case 3 : {
      // Command 3 : read a byte (send a dummy byte out)
      RXByte = SPI.transfer(0x00);
      Serial.print("In : ");
      Serial.println(RXByte,HEX);
      break;      
    }
    default : {
      Serial.println("Invalid choice");
    }
  }
  delay(100);
}
int showMenu(String Menu[],int MenuItemCount)
{
  Serial.flush();
  Serial.println("Please select from one of the following:");
  for (int item=0; item < MenuItemCount; item++)
  {
    Serial.print(item);
    Serial.print(": ");
    Serial.println(Menu[item]);
  }
  while(Serial.available()==0);
    
  return Serial.read() - '0'; // assuming a numeric choice is made - convert to decimal from ascii
}

int getUserCommand()
{
  String Menu[4];
  Menu[0]="SS Low";
  Menu[1]="SS High";
  Menu[2]="Write byte";
  Menu[3]="Read byte";
  return showMenu(Menu,4);
  
}
int HexDigitToDecimal(char Digit)
{
  if ( (Digit >= '0') && (Digit <= '9') )
  {
    return Digit - '0';
  }
  Digit = Digit | 32; // enforce lower case
  if ( (Digit >= 'a') && (Digit <= 'f') )
  {
    return Digit - 'a' + 10;
  }
  return 0;
}
int getInteger(String Prompt)
{
  char HexString[3];
  int ReturnValue = 0;
  HexString[2]=0;
  Serial.flush();
  Serial.print("Enter a 2 character hex value: ");
  while(Serial.available()==0);  
  HexString[0]=Serial.read();Serial.print(HexString[0]);
  while(Serial.available()==0);  
  HexString[1]=Serial.read();Serial.println(HexString[1]);
  ReturnValue = HexDigitToDecimal(HexString[0]);
  ReturnValue = ReturnValue << 4;
  ReturnValue += HexDigitToDecimal(HexString[1]);
  return ReturnValue;
}


Let your code do the wiring

SimpleVsComplex

The image above shows two implementations of the same gaming system (ArcadeSlam). The display has a parallel data interface and the left hand version maps this interface to the 8 bits of a single I/O port on the MSP430 MCU.  A simple write to the port data register is sufficient to write a byte to the display.  From a programming perspective this is easy but, as you can see, the wiring is a little complex.

The version on the right makes use of the connections within the breadboard to connect the display data interface to the MSP430.  This greatly simplifies the wiring however it pushes this complexity back into the code.  The wiring looks like this:

Wiring

The display data interface is spread across Ports 1 and 2.  Not only that, the bits are in reverse order.  Reversing bits at run-time represents a performance hit so, a lookup table was generated and the writing of the data bytes goes from this (for the left hand version)


P2OUT = data;

to

P1OUT &=0xc1;
P2OUT &=0xf8;
if (b)
{ // only write out bits if b is non zero to save time
P1OUT |= reverse_bits[ (b >> 3) ] >> 2;
P2OUT |= reverse_bits[ (b & 0x7) ] >> 5;
}

The lookup table reverse_bits was produced using the following python script (only a 5 bit table was necessary)


#!/usr/bin/python
# Output the specified range of numbers with their
# bits reversed as a lookup table suitable for C
print "const uint8_t reverse_bits[]={ \\"
for n in range(32):
print int('{:08b}'.format(n)[::-1], 2),",\\"
print "};"

Performance is not obviously affected by this wiring change and full code can be downloaded over here on github.

More information can also be found on roboslam.com