Pages

2010-10-12

Embedded: SPI Bitbanging

#define CLKLOW()       // Put SCLK GPIO to LOW

#define CLKHIGH()      // Put SCLK GPIO to HIGH

#define ASSERTCS()     // Put /CS GPIO to LOW

#define DEASSERTCS()   // Put /CS GPIO to HIGH

#define READMISO()     // MISO GPIO status?

#define MOSIHIGH()     // MOSI GPIO to HIGH
#define MOSILOW()      // MOSI GPIO to LOW
#define POWERON()      // VCC GPIO to HIGH

#define POWERDOWN      // VCC GPIO to LOW

#define SPISPPED       140

void spi_init()
{
    POWERON();
    CLKHIGH();
    DEASSERTCS();  
}
/////////////////////////////////////////////////////////////////////////////////////////////////
void spi_write_byte_SPIBitBang8BitsMode0(unsigned char byte)
{       
    unsigned char bit;
    ASSERTCS();
    for (bit = 0; bit < 8; bit++) {
        /* write MOSI on trailing edge of previous clock */
        if (byte & 0x80)
            MOSIHIGH();
        else
            MOSILOW();
        byte <<= 1;
 
        /* half a clock cycle before leading/rising edge */
        SPIDELAY(SPISPEED/2);
        CLKHIGH();
 
        /* half a clock cycle before trailing/falling edge */
        SPIDELAY(SPISPEED/2);
 
        /* read MISO on trailing edge */
        //byte |= READMISO();
        CLKLOW();
    } 
    DEASSERTCS();

}
/////////////////////////////////////////////////////////////////////////////////////////////////
void spi_write_byte(unsigned char byte)   /* Pseudo Code */
{
    TEMP = 100000000B;
    SS = 0;
    SCK = 1; 
   WHILE(TEMP)
       MOSI = (WRITE_BUFFER && TEMP);
       TEMP >> 1;
       SCK ^= 1;
   END WHILE
   SS = 1
}
/////////////////////////////////////////////////////////////////////////////////////////////////
unsigned char spi_read_byte()   /* Pseudo Code */
{
   SS = 0;
   SCK = 1;
   Count = 8;
   WHILE(count)
      READ_BUFFER | = MISO;
      READ_BUFFER << 1;
      Count--;
      SCK ^= 1;
   END WHILE
   SS = 1
}
////////////////////////
void spi_stop()
{
   POWERDOWN();
}
For more information on SPI, please visit this Wikipedia article

No comments:

Post a Comment