-1

I'm trying to get the SPI working on a PIC32MX250F128D without much luck.

I tried in 8 bit mode and 32 bit mode, but I'm not getting all the data or no data at all.

I'm trying to use a 4MHz SPI to drive a WS2812 ledstrip.

This is the code I have:

#include <xc.h>
#include <peripheral/system.h>
#include "config.h"

void settings( void );
char Send_SPI(unsigned char);

int main( void ) {
    int i, j;
    unsigned char scrapdata;
    unsigned char buffer[6] = {0x12, 0x34, 0x56, 0x78, 0x90, 0x01};

    settings();

    while(1) {
        Send_SPI(buffer[j]);
        j = (j > 4)? 0 : j++;
        for(i = 0; i < 300; i++);
    }

    return 0;
}

void settings( void ) {
    SYSTEMConfigPerformance(SYS_FREQ);
    TRISB &= 0xFFFB;
    RPB2R = 0x3;

    SPI1STAT = 0;
    SPI1CON = 0;
    unsigned int rData = SPI1BUF;

    // => 4MHz = 48MHz / (2 * (5 + 1))
    SPI1BRG = 5;
    SPI1STATCLR = 0x40; // clear the Overflow
    SPI1CON = 0x00008230;
}

char Send_SPI(unsigned char buffer) {
    //while(!(SPI1STAT & 0x2));
    SPI1BUF = buffer;
    while(!(SPI1STAT & 0x1)); // wait transfer complete 
    char scrapdata = SPI1BUF; //read to clear SPI2BUF before reload
    return scrapdata;
}

At the moment there is nothing coming out of the controller. Does anyone of you know what's wrong?

Laurens

2 Answers2

0

You never initialized j before using it in main() meaning you're probably sending out gibberish at first. Also the result of your ternary operation j = (j > 4)? 0 : j++; is not clearly defined since you're basically saying j = j++ at some point. Make it simpler with:

if (j > 4) j = 0;
else j++;

Finally, test your SPI initialization code with a shift register and a bunch of LEDs to be sure it's all good. A logic analyzer would also help see what signals, if any, are being sent out by the MCU.

SoreDakeNoKoto
  • 1,175
  • 1
  • 9
  • 16
0

Try oscilloscope and check if you are getting the CS and SCK signals, if not SPI is not initialized! But with the PIC family there are many painless ways to write SPI:

  • Easiest way will be using SPI.h given by the compiler.
  • You can also use the MCC(MPLAB code configurator) plug-in to write a SPI driver
  • Use bit banging, something like this:

    char SPI_BB(char byte8) {
        char counter;
        for (counter = 8; counter; counter--) {
            if (byte8 & 0x80)
                MOSI=1;
            else
                MOSI=0;
            byte8 <<= 1;
            SCK=1; /* a slave latches input data bit */
            if ((MIS0))
                byte8 |= 0x01;
            SCK=0; /* a slave shifts out next output data bit */
        }
        return byte8;
    }
    

The above code is in SPI mode 0.

nikhil patil
  • 142
  • 1
  • 12