What is SPI and how do we use it on the PIC32MZ?
Last time I covered Peripheral Pin Select, and this is something that will be needed in today's post about using SPI so if you don't know about it I suggest you read the previous post first.
SPI or Serial Peripheral Interface is a way of communicating with an external device using 3 or 4 wires, depending on whether we way one-way or two-way communication. A simple look in the infamous PIC32 datasheet under SPI reveals yet another extra datasheet we need to download, in this case entitled DS60001106. So fine, we download that and look at what pins SPI uses and we eventually get to this:

With SPI, there is a Master device and a Slave device. The master device is the one that controls the transaction and needs to send a clock signal to the slave device. If you come from Arduino the naming is a little different:
- SDI here means data into the PIC32 from some other device and in my example would also be known as MISO (Master In, Slave Out)
- SDO means data out of the PIC32 and to another device and in my example would also be known as MOSI (Master Out, Slave In)
- SCK is the clock signal and the name is pretty common across all platforms.
- SS is slave select, also known as CS (Chip Select).
An important thing to remember about SPI is that the master is the only one that can generate the clock signal. This means that if you want to get device from an SPI module or SD card or whatever, you have to send it data in order for it to get the clock signal it needs to send you some data back. The sending and receiving of data is done at the same time because there is a dedicated wire for each (namely, SDI and SDO). For example, let's look at the following scenario: I have an 8-bit SPI connected LCD, and I want to read pixel 1 from its display memory. The command to do this is 0xFE followed by the pixel number, which is 0x0001 (a 16-bit number). I'd send the following data:
- Send 0xFE, ignore reply.
- Send 0x00, ignore reply.
- Send 0x01, ignore reply.
Now the slave device has the command and the parameter, it needs time to process the data before it can respond. Some devices can do this instantly, but some need a few clock cycles in order to process it because they depend entirely on this clock signal to operate at all. In my example, the LCD needs 3 clock cycles before it can reply with a 16-bit number. So to give it three cycles, I need to send it dummy data. I've chosen to send 0xFF and it may be different depending on the peripheral but everything I've seen was fine with 0xFF. So now we have to:
- Send 0xFF, ignore reply.
- Send 0xFF, ignore reply.
- Send 0xFF, ignore reply.
OK, now the LCD is ready to send me a 16-bit number back. I'm in 8-bit mode so this means 2 clock cycles.
- Send 0xFF, store reply as high 8-bits.
- Send 0xFF, store reply as low 8-bits
- Combine words: result = (high << 8) | low;
So a simple transaction can actually take a long time. This is how all SPI transactions work, and needs to be kept in mind.
One of the cool things about SPI is we can attach multiple devices to the SDI, SDO and SCK wires at the same time. With this system, each attached device would need a dedicated Chip Select pin of its own. For example, RA0 could be chip select for an SD memory card, RA1 could be chip select for an SPI LCD, etc. Because of this, in most of my SPI projects where the PIC32 is acting in the role of master I do not use the SPI peripheral's SS pin I just assign it to whichever port is convenient to me. Note: In I2S (Inter-IC Sound) we usually have to use the SS pin as it generates a special clock signal. That's beyond the scope of today's blog post however.
This is going to be a two-part post and the eventual goal is to attach an SD card to my PIC32MZ and read the first 128 bytes from a file named "test.txt" in the root directory. We will be making use of the excellent FatFs library - available here - to access and read the file so the SD card must be FAT or FAT32 formatted. This is actually quite an involved process so today I'm just going to look at setting up and using the SPI peripheral.
OK phew, explanation of what we want to do out of the way, let's move on to choosing which pins we want to use the SPI peripheral on. After all, according to the datasheet there are "Six 4-wire SPI modules (up to 50 MHz)" so we're spoiled for choice. And if you believe that, you haven't been burned by PIC32MZ badly enough yet (or haven't been shopping). Way, waaaaaay down in the datasheet you'll see why it says "up to 50Mhz."

Waaah Waah Waah Waaaaaaaaah. Oh, and let's not forget that little note number 5!
"5: To achieve maximum data rate, VDD must be ≥ 3.3V, the SMP bit (SPIxCON<9>) must be equal to ‘1’, and the operating temperature must be within the range of -40°C to +105°C."
And let me guess, additionally, it must be the night of the second full moon of the month and between 9PM and 11PM on a Tuesday, right? Naturally, we want to access the SD card at 50Mhz and not 25Mhz. Nothing is ever easy and straightforward with the PIC32MZ. Anyway, in my example I'm going to be using SPI2, with SDI on RB3, SDO on RB5 and CS on RB4. The SCK2 pin is not movable via Peripheral Pin Select, and on the 144-pin chip I use it is always on pin 14 (RG6). OK, let's set up PPS for SDO2 and SDI2:
SDI2R = 0b1000; // RB3 = SDI2
RPB5R = 0b0110; // RB5 = SDO2
TRISBbits.TRISB3 = 1; // Set RB3 as input because it's SDI2
PPS out the way, let's look at actually setting up SPI2 peripheral. On the PIC32MX with PLIB we used to do this:
SpiChnOpen(SPI_CHANNEL2,SPI_OPEN_MSTEN | SPI_OPEN_CKP_HIGH | SPI_OPEN_SMP_END | SPI_OPEN_MODE8, 64);
If you want to do this on the PIC32MZ, there is no PLIB so you can use the following code to do the same thing, with one small difference:
void SPI_init()
{
SPI2CONbits.ON = 0; // Turn off SPI2 before configuring
SPI2CONbits.MSTEN = 1; // Enable Master mode
SPI2CONbits.CKP = 1; // Clock signal is active low, idle state is high
SPI2CONbits.CKE = 0; // Data is shifted out/in on transition from idle (high) state to active (low) state
SPI2CONbits.SMP = 1; // Input data is sampled at the end of the clock signal
SPI2CONbits.MODE16 = 0; // Do not use 16-bit mode
SPI2CONbits.MODE32 = 0; // Do not use 32-bit mode (combines with the above line to activate 8-bit mode)
SPI2BRG = 0; // Set Baud Rate Generator to 0 [discussed below]
SPI2CONbits.ENHBUF = 0; // Disables Enhanced Buffer mode [also discussed below]
SPI2CONbits.ON = 1; // Configuration is done, turn on SPI2 peripheral
}
This will setup the SPI2 port as a master in 8-bit mode at 50Mhz using the standard polarities devices expect. For more explanation, we turn to...
TL;DR
The SPI2BRG register controls the speed of the SPI peripheral, and it is controlled by the following formula from the manual:

A while ago I discussed how different peripheral bus clocks control different peripherals. In this case, Peripheral Bus Clock 2 controls both the UART and the SPI. We set the peripheral bus clock 2 to 100Mhz during the initialisation. The smallest we can set SPI2BRG to is 0, which means the fastest speed we can get is (100/2*(0+1)), which is 100/2 which is 50Mhz. Every time the clock signal changes from high to low a bit is transmitted/received, so let's look at the actual byte transfer rates we can expect. We have a maximum of 50Mbps in 8-bit mode, which is 50mbps / 8 = 6.25MB/s at an absolute maximum, though in reality we won't be getting near this rate and I've found we usually get somewhere around 4MB/s reliably with my file transfers.
The Enhanced Buffer mode enables a 16-byte deep FIFO (First In First Out) buffer, which enables us to load up 16 bytes of data before the sending even begins. In practice this saves a huge amount of time and gives us faster transfer rates because the SPI peripheral has less time when it is doing nothing and just waiting for us to give it data to send.
OK, SETUP IS DONE! Now how do we use it to send data? Thankfully, its dead simple to use. If we want to send a character stored in the data variable to SPI2 we can do it like this:
char SPI_send(char data)
{
SPI2BUF = data; // Send **data** to SPI2BUF.
while (SPI2STATbits.SPIRBE); // Which the receive buffer is empty, loop
return (char)SPI2BUF; // Return whatever is in SPI2BUF
}
TL;DR
A note on Enhanced Buffer Mode: We don't use SPI2STATbits.SPIRBE when in enhanced buffer mode, instead we check the value of SPI2STATbits.RXBUFELM, which tells us how many elements (bytes) are stored in the receive buffer. If I send 16 bytes like this:
int cnt;
for (cnt = 0; cnt < 16; cnt++)
{
SPI2BUF = 0xFF;
}
The SPI2 peripheral will start sending data. At the very beginning, the value of SPI2STATbits.TXBUFELM will be 16 because it has 16 bytes queued up, and the value of SPI2STATbits.RXBUFELM will be 0 because it hasn't received anything yet. As it process the 16 bytes automatically, eventually SPI2STATbits.TXBUFELM will move down to 0. As it moves down to 0, SPI2STATbits.RXBUFELM will move up to 16 as it receives the replies. I can then read the data as follows:
int cnt;
char data[16];
for (cnt = 0; cnt < 16; cnt++)
{
data[cnt] = SPI2BUF;
}
As soon as I read from SPI2BUF, the peripheral automatically removes the top entry from the buffer, puts the next value in SPI2BUF and reduces RXBUFELM by 1.
A very important note about the timing of sending and receiving data
When we send data via SPI, we always get some data back immediately but it is vital that you remember this reply data is actually the reply to the previously sent data byte. For most transactions, this doesn't matter. We often just want to send tons of data and the replies from the slave device are not important. However, when we are working with something where the replies are important, this can be a potentially dangerous trap. As such, there are a lot of "dummy" bytes sent in SPI transactions in order to give the slave the clock signals it needs to reply, and the dummy bytes are often 0xFF.
Wow, that was way more complicated that I intended it to be. Next time we'll use this code and understanding of SPI to communicate with an SD card.
20 comments
Adan
First off, great site! I really enjoy your work.
I'm working on SPI with the Pic32mz. I'm attempting to communicate via SPI (from SPI2 [master] to SPI1 [slave] ) in a loop on the same board as indicated by the picture attached (mz ef starter kit + expansion IO board), just to see if I have it working properly.
My master appeared to be properly sending data; however, when I disconnect the SCK, the data still runs (I used your work in the UART example to communicate my SPI output to an Arduino for debugging, which works properly) which I find fishy.
Another aspect that has me confused is if I wait for data to be received (by the master) with this line -> while(!SPI2STATbits.SPIRBF){ }, it continues to loop; however, with this line (by the slave) -> while(!SPI1STATbits.SPIRBF){ }, it doesn't run.
Attached my code below. Thanks again for any help.
// DEVCFG3
// USERID = No Setting
#pragma config FMIIEN = ON // Ethernet RMII/MII Enable (MII Enabled)
#pragma config FETHIO = ON // Ethernet I/O Pin Select (Default Ethernet I/O)
#pragma config PGL1WAY = OFF // Permission Group Lock One Way Configuration (Allow multiple reconfigurations)
#pragma config PMDL1WAY = OFF // Peripheral Module Disable Configuration (Allow multiple reconfigurations)
#pragma config IOL1WAY = OFF // Peripheral Pin Select Configuration (Allow multiple reconfigurations)
#pragma config FUSBIDIO = OFF // USB USBID Selection (Controlled by Port Function)
// DEVCFG2
#pragma config FPLLIDIV = DIV_3 // System PLL Input Divider (3x Divider)
#pragma config FPLLRNG = RANGE_5_10_MHZ // System PLL Input Range (5-10 MHz Input)
#pragma config FPLLICLK = PLL_POSC // System PLL Input Clock Selection (POSC is input to the System PLL)
#pragma config FPLLMULT = MUL_50 // System PLL Multiplier (PLL Multiply by 50)
#pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider (2x Divider)
#pragma config UPLLFSEL = FREQ_24MHZ // USB PLL Input Frequency Selection (USB PLL input is 24 MHz)
// DEVCFG1
#pragma config FNOSC = SPLL // Oscillator Selection Bits (System PLL)
#pragma config DMTINTV = WIN_127_128 // DMT Count Window Interval (Window/Interval value is 127/128 counter value)
#pragma config FSOSCEN = OFF // Secondary Oscillator Enable (Disable SOSC)
#pragma config IESO = OFF // Internal/External Switch Over (Disabled)
#pragma config POSCMOD = EC // Primary Oscillator Configuration (External clock mode)
#pragma config OSCIOFNC = OFF // CLKO Output Signal Active on the OSCO Pin (Disabled)
#pragma config FCKSM = CSECME // Clock Switching and Monitor Selection (Clock Switch Enabled, FSCM Enabled)
#pragma config WDTPS = PS1048576 // Watchdog Timer Postscaler (1:1048576)
#pragma config WDTSPGM = STOP // Watchdog Timer Stop During Flash Programming (WDT stops during Flash programming)
#pragma config WINDIS = NORMAL // Watchdog Timer Window Mode (Watchdog Timer is in non-Window mode)
#pragma config FWDTEN = OFF // Watchdog Timer Enable (WDT Disabled)
#pragma config FWDTWINSZ = WINSZ_25 // Watchdog Timer Window Size (Window size is 25%)
#pragma config DMTCNT = DMT31 // Deadman Timer Count Selection (2^31 (2147483648))
#pragma config FDMTEN = OFF // Deadman Timer Enable (Deadman Timer is disabled)
// DEVCFG0
#pragma config DEBUG = OFF // Background Debugger Enable (Debugger is disabled)
#pragma config JTAGEN = OFF // JTAG Enable (JTAG Disabled)
#pragma config ICESEL = ICS_PGx1 // ICE/ICD Comm Channel Select (Communicate on PGEC1/PGED1)
#pragma config TRCEN = OFF // Trace Enable (Trace features in the CPU are disabled)
#pragma config BOOTISA = MIPS32 // Boot ISA Selection (Boot code and Exception code is MIPS32)
#pragma config FECCCON = OFF_UNLOCKED // Dynamic Flash ECC Configuration (ECC and Dynamic ECC are disabled (ECCCON bits are writable))
#pragma config FSLEEP = OFF // Flash Sleep Mode (Flash is powered down when the device is in Sleep mode)
#pragma config DBGPER = PG_ALL // Debug Mode CPU Access Permission (Allow CPU access to all permission regions)
#pragma config SMCLR = MCLR_NORM // Soft Master Clear Enable bit (MCLR pin generates a normal system Reset)
#pragma config SOSCGAIN = GAIN_2X // Secondary Oscillator Gain Control bits (2x gain setting)
#pragma config SOSCBOOST = OFF // Secondary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
#pragma config POSCGAIN = GAIN_2X // Primary Oscillator Gain Control bits (2x gain setting)
#pragma config POSCBOOST = OFF // Primary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
#pragma config EJTAGBEN = NORMAL // EJTAG Boot (Normal EJTAG functionality)
#pragma config CP = OFF // Code Protect (Protection Disabled)
#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <proc p32mz2048efh144.h="">
#define SYS_FREQ 200000000 // Running at 200MHz
void set_performance_mode()
{
unsigned int cp0;
// Unlock Sequence
asm volatile("di"); // Disable all interrupts
SYSKEY = 0xAA996655;
SYSKEY = 0x556699AA;
// PB1DIV
// Peripheral Bus 1 cannot be turned off, so there's no need to turn it on
PB1DIVbits.PBDIV = 1; // Peripheral Bus 1 Clock Divisor Control (PBCLK1 is SYSCLK divided by 2)
// PB2DIV
PB2DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
PB2DIVbits.PBDIV = 1; // Peripheral Bus 2 Clock Divisor Control (PBCLK2 is SYSCLK divided by 2)
// PB3DIV
PB3DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
PB3DIVbits.PBDIV = 1; // Peripheral Bus 3 Clock Divisor Control (PBCLK3 is SYSCLK divided by 2)
// PB4DIV
PB4DIVbits.ON = 1; // Peripheral Bus 4 Output Clock Enable (Output clock is enabled)
while (!PB4DIVbits.PBDIVRDY); // Wait until it is ready to write to
PB4DIVbits.PBDIV = 0; // Peripheral Bus 4 Clock Divisor Control (PBCLK4 is SYSCLK divided by 1)
// PB5DIV
PB5DIVbits.ON = 1; // Peripheral Bus 5 Output Clock Enable (Output clock is enabled)
PB5DIVbits.PBDIV = 1; // Peripheral Bus 5 Clock Divisor Control (PBCLK5 is SYSCLK divided by 2)
// PB7DIV
PB7DIVbits.ON = 1; // Peripheral Bus 7 Output Clock Enable (Output clock is enabled)
PB7DIVbits.PBDIV = 0; // Peripheral Bus 7 Clock Divisor Control (PBCLK7 is SYSCLK divided by 1)
// PB8DIV
PB8DIVbits.ON = 1; // Peripheral Bus 8 Output Clock Enable (Output clock is enabled)
PB8DIVbits.PBDIV = 1; // Peripheral Bus 8 Clock Divisor Control (PBCLK8 is SYSCLK divided by 2)
// PRECON - Set up prefetch
PRECONbits.PFMSECEN = 0; // Flash SEC Interrupt Enable (Do not generate an interrupt when the PFMSEC bit is set)
PRECONbits.PREFEN = 0b11; // Predictive Prefetch Enable (Enable predictive prefetch for any address)
PRECONbits.PFMWS = 0b010; // PFM Access Time Defined in Terms of SYSCLK Wait States (Two wait states)
// Set up caching
cp0 = _mfc0(16, 0);
cp0 &= ~0x07;
cp0 |= 0b011; // K0 = Cacheable, non-coherent, write-back, write allocate
_mtc0(16, 0, cp0);
// Lock Sequence
SYSKEY = 0x33333333;
asm volatile("ei"); // Enable all interrupts
}
void delay_us(unsigned int us)
{
// Convert microseconds us into how many clock ticks it will take
us *= SYS_FREQ / 1000000 / 2; // Core Timer updates every 2 ticks
_CP0_SET_COUNT(0); // Set Core Timer count to 0
while (us > _CP0_GET_COUNT()); // Wait until Core Timer count reaches the number we calculated earlier
}
void delay_ms(int ms)
{
delay_us(ms * 1000);
}
// Initialise peripheral UART 6
void UART_Init()
{
int pbClk;
pbClk = SYS_FREQ / 2; // Our PBCLK2 divider was set to 1, so PBCLK2 is exactly half the speed of the system clock, or 100Mhz
U6MODE = 0; // Set UART 6 off prior to setting it up
U6MODEbits.BRGH = 0; // We want standard speed mode. Not necessary as we just set U6MODE to 0 so this is just for explanation's sake
U6BRG = pbClk / (16 * 38400) - 1;// This is the formula straight from the datasheet
U6STA = 0; // Disable the TX and RX pins, clear all flags
U6STAbits.UTXEN = 1; // Enable the TX pin
U6STAbits.URXEN = 1; // Enable the RX pin
U6MODEbits.PDSEL = 0; // PDSEL controls how many data bits and how many parity bits we want, this is the default of 8-bit data, no parity bits that most terminals use
U6MODEbits.STSEL = 0; // STSEL controls how many stop bits we use, let's use the default of 1
U6MODEbits.ON = 1; // Turn on the UART 6 peripheral
}
// Overwrite _mon_putc() to enable us to use printf
void _mon_putc (char c)
{
while (U6STAbits.UTXBF); // Wait til current transmission is complete
U6TXREG = c;
}
/*
*
*/
int main() {
// Set up all ports to be digital and not analog
ANSELA = 0;
ANSELB = 0;
ANSELC = 0;
ANSELD = 0;
ANSELE = 0;
ANSELF = 0;
ANSELG = 0;
ANSELH = 0;
ANSELJ = 0;
// Initialise peripheral UART 6
UART_Init();
// Set up PPS for UART 6
U6RXR = 0b1100; // RC2 = U6RX
RPD4R = 0b0100; // RD4 = U6TX
TRISCbits.TRISC2 = 1; // Make RC2 (U6RX) an input
TRISDbits.TRISD4 = 0; // Make RD4 (U6TX) an output
char buf[100] = {};
// master
SPI2CONbits.ON = 0; // Turn off SPI2 before configuring
SPI2CONbits.MSTEN = 1; // master mode
SPI2CONbits.CKP = 1; // Clock signal is active low, idle state is high
SPI2CONbits.CKE = 0; // Data is shifted out/in on transition from idle (high) state to active (low) state
SPI2CONbits.SMP = 1; // Input data is sampled at the end of the clock signal
SPI2CONbits.MODE32 = 0; // use 16 bit mode
SPI2CONbits.MODE16 = 1;
//SPI2BUF; // clear rx buffer by reading it
SPI2BRG = 0x06; // baud rate to 8 MHz
SPI2CONbits.ENHBUF = 0; // Disables Enhanced Buffer mode [also discussed below]
//SPI2STATbits.SPIROV = 0; // clear overflow bit
SPI2CONbits.ON = 1; // turn on master
// slave
SPI1CONbits.ON = 0; // Turn off SPI1 before configuring
SPI1CONbits.MSTEN = 0; // save mode
SPI1CONbits.MODE32 = 0;
SPI1CONbits.MODE16 = 1;
//SPI1BUF; // clear the buffer
//SPI1STATbits.SPIROV = 0; // clear the overflow
SPI1CONbits.ON = 1; // turn on slave, slave mode do not set baud rate
// Set up PPS for SPI2 on RB3 and RB5
SDI2R = 0b1000; // RB3 = SDI2
// RPB5R = 0b0110; // RB5 = SDO2
TRISBbits.TRISB3 = 1; // Set RB3 as input because it's SDI2
int count = 0;
while(1){
unsigned short master = 0, slave = 0;
unsigned short rmaster = 0, rslave = 0;
master += count;
//slave += count;
printf("beginning master and slave SPI communication.\n");
// have the slave write its data to its SPI buffer, data will not be sent until master performs a write
SPI1BUF = slave;
// have master perform a write
SPI2BUF = master;
// wait until data is received
while(!SPI2STATbits.SPIRBF){ }
//while(!SPI1STATbits.SPIRBF){ }
// receive the data
rmaster = SPI2BUF;
rslave = SPI1BUF;
sprintf(buf, "Master sent 0x%04x, Slave sent 0x%04x\r\n", master, slave);
printf(buf);
sprintf(buf, "Slave read 0x%04x, Master read 0x%04x\r\n", rslave, rmaster);
printf(buf);
count++;
}
return (EXIT_SUCCESS);
} https://uploads.disquscdn.com/images/797d698ff3b2c261591bf613912884533d28d8f437bea2957964367b54195746.jpg https://uploads.disquscdn.com/images/c54b995725c904a2bdd85195736225a679fdd9c0ecda03b65f7567dbbc1a1d12.jpg
Adan
Not sure this helps, but the pins I am using are:
SDI2: RD7, SD02: RB5, SCLK2: RG6
SDI1: RD14, SDO1: RD10, SCLK1: RD1
UartTx6:RD4, UartRx6: RC2
Aidan Author
Hi Adan,
First off, nice name :) Before we go further you're going to need to set up the PPS pins for SP1 too. You have the SPI2 pins set up correctly:
SDI2R = 0b1000; // RB3 = SDI2
// Uncomment this line
RPB5R = 0b0110; // RB5 = SDO2
TRISBbits.TRISB3 = 1; // Set RB3 as input because it's SDI2
But you have nothing for SPI1. Add these lines:
SDI1R = 0b1011; // RD14 = SDI1
RPD10R = 0b0101; // RD10 = SDO1
TRISDbits.TRISD14 = 1; // Set RD14 as input because it's SDI1
SCK1 and SCK2 are fixed so we can't change their pin numbers or turn them off. If we turn on the SPI peripheral the SCK pin will automatically be assigned and start to work.
Give that a go and let me know if it works.
Adan
Thanks for the quick response. The master is now able to send and receive data from the slave. However, the slave is unable to read from the master. I tried changes a few of the pins to see if it was a pin configuration issue; however, this was consistent.
Pin configuration: SDI2: RD7, SDO2: RB5, SCLK2: RG6, SDI1: RA14, SDO1:RD10, SCLK1: RD1
I also attached an image of the output on the arduino, which seems correct based upon the explanation above. It gets hung when I uncomment this line, which makes sense if the slave is not reading, -> while(!SPI1STATbits.SPIRBF){ }.
https://uploads.disquscdn.c....
// DEVCFG3
// USERID = No Setting
#pragma config FMIIEN = ON // Ethernet RMII/MII Enable (MII Enabled)
#pragma config FETHIO = ON // Ethernet I/O Pin Select (Default Ethernet I/O)
#pragma config PGL1WAY = OFF // Permission Group Lock One Way Configuration (Allow multiple reconfigurations)
#pragma config PMDL1WAY = OFF // Peripheral Module Disable Configuration (Allow multiple reconfigurations)
#pragma config IOL1WAY = OFF // Peripheral Pin Select Configuration (Allow multiple reconfigurations)
#pragma config FUSBIDIO = OFF // USB USBID Selection (Controlled by Port Function)
// DEVCFG2
#pragma config FPLLIDIV = DIV_3 // System PLL Input Divider (3x Divider)
#pragma config FPLLRNG = RANGE_5_10_MHZ // System PLL Input Range (5-10 MHz Input)
#pragma config FPLLICLK = PLL_POSC // System PLL Input Clock Selection (POSC is input to the System PLL)
#pragma config FPLLMULT = MUL_50 // System PLL Multiplier (PLL Multiply by 50)
#pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider (2x Divider)
#pragma config UPLLFSEL = FREQ_24MHZ // USB PLL Input Frequency Selection (USB PLL input is 24 MHz)
// DEVCFG1
#pragma config FNOSC = SPLL // Oscillator Selection Bits (System PLL)
#pragma config DMTINTV = WIN_127_128 // DMT Count Window Interval (Window/Interval value is 127/128 counter value)
#pragma config FSOSCEN = OFF // Secondary Oscillator Enable (Disable SOSC)
#pragma config IESO = OFF // Internal/External Switch Over (Disabled)
#pragma config POSCMOD = EC // Primary Oscillator Configuration (External clock mode)
#pragma config OSCIOFNC = OFF // CLKO Output Signal Active on the OSCO Pin (Disabled)
#pragma config FCKSM = CSECME // Clock Switching and Monitor Selection (Clock Switch Enabled, FSCM Enabled)
#pragma config WDTPS = PS1048576 // Watchdog Timer Postscaler (1:1048576)
#pragma config WDTSPGM = STOP // Watchdog Timer Stop During Flash Programming (WDT stops during Flash programming)
#pragma config WINDIS = NORMAL // Watchdog Timer Window Mode (Watchdog Timer is in non-Window mode)
#pragma config FWDTEN = OFF // Watchdog Timer Enable (WDT Disabled)
#pragma config FWDTWINSZ = WINSZ_25 // Watchdog Timer Window Size (Window size is 25%)
#pragma config DMTCNT = DMT31 // Deadman Timer Count Selection (2^31 (2147483648))
#pragma config FDMTEN = OFF // Deadman Timer Enable (Deadman Timer is disabled)
// DEVCFG0
#pragma config DEBUG = OFF // Background Debugger Enable (Debugger is disabled)
#pragma config JTAGEN = OFF // JTAG Enable (JTAG Disabled)
#pragma config ICESEL = ICS_PGx1 // ICE/ICD Comm Channel Select (Communicate on PGEC1/PGED1)
#pragma config TRCEN = OFF // Trace Enable (Trace features in the CPU are disabled)
#pragma config BOOTISA = MIPS32 // Boot ISA Selection (Boot code and Exception code is MIPS32)
#pragma config FECCCON = OFF_UNLOCKED // Dynamic Flash ECC Configuration (ECC and Dynamic ECC are disabled (ECCCON bits are writable))
#pragma config FSLEEP = OFF // Flash Sleep Mode (Flash is powered down when the device is in Sleep mode)
#pragma config DBGPER = PG_ALL // Debug Mode CPU Access Permission (Allow CPU access to all permission regions)
#pragma config SMCLR = MCLR_NORM // Soft Master Clear Enable bit (MCLR pin generates a normal system Reset)
#pragma config SOSCGAIN = GAIN_2X // Secondary Oscillator Gain Control bits (2x gain setting)
#pragma config SOSCBOOST = OFF // Secondary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
#pragma config POSCGAIN = GAIN_2X // Primary Oscillator Gain Control bits (2x gain setting)
#pragma config POSCBOOST = OFF // Primary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
#pragma config EJTAGBEN = NORMAL // EJTAG Boot (Normal EJTAG functionality)
#pragma config CP = OFF // Code Protect (Protection Disabled)
#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <proc p32mz2048efh144.h="">
#define SYS_FREQ 200000000 // Running at 200MHz
void set_performance_mode()
{
unsigned int cp0;
// Unlock Sequence
asm volatile("di"); // Disable all interrupts
SYSKEY = 0xAA996655;
SYSKEY = 0x556699AA;
// PB1DIV
// Peripheral Bus 1 cannot be turned off, so there's no need to turn it on
PB1DIVbits.PBDIV = 1; // Peripheral Bus 1 Clock Divisor Control (PBCLK1 is SYSCLK divided by 2)
// PB2DIV
PB2DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
PB2DIVbits.PBDIV = 1; // Peripheral Bus 2 Clock Divisor Control (PBCLK2 is SYSCLK divided by 2)
// PB3DIV
PB3DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
PB3DIVbits.PBDIV = 1; // Peripheral Bus 3 Clock Divisor Control (PBCLK3 is SYSCLK divided by 2)
// PB4DIV
PB4DIVbits.ON = 1; // Peripheral Bus 4 Output Clock Enable (Output clock is enabled)
while (!PB4DIVbits.PBDIVRDY); // Wait until it is ready to write to
PB4DIVbits.PBDIV = 0; // Peripheral Bus 4 Clock Divisor Control (PBCLK4 is SYSCLK divided by 1)
// PB5DIV
PB5DIVbits.ON = 1; // Peripheral Bus 5 Output Clock Enable (Output clock is enabled)
PB5DIVbits.PBDIV = 1; // Peripheral Bus 5 Clock Divisor Control (PBCLK5 is SYSCLK divided by 2)
// PB7DIV
PB7DIVbits.ON = 1; // Peripheral Bus 7 Output Clock Enable (Output clock is enabled)
PB7DIVbits.PBDIV = 0; // Peripheral Bus 7 Clock Divisor Control (PBCLK7 is SYSCLK divided by 1)
// PB8DIV
PB8DIVbits.ON = 1; // Peripheral Bus 8 Output Clock Enable (Output clock is enabled)
PB8DIVbits.PBDIV = 1; // Peripheral Bus 8 Clock Divisor Control (PBCLK8 is SYSCLK divided by 2)
// PRECON - Set up prefetch
PRECONbits.PFMSECEN = 0; // Flash SEC Interrupt Enable (Do not generate an interrupt when the PFMSEC bit is set)
PRECONbits.PREFEN = 0b11; // Predictive Prefetch Enable (Enable predictive prefetch for any address)
PRECONbits.PFMWS = 0b010; // PFM Access Time Defined in Terms of SYSCLK Wait States (Two wait states)
// Set up caching
cp0 = _mfc0(16, 0);
cp0 &= ~0x07;
cp0 |= 0b011; // K0 = Cacheable, non-coherent, write-back, write allocate
_mtc0(16, 0, cp0);
// Lock Sequence
SYSKEY = 0x33333333;
asm volatile("ei"); // Enable all interrupts
}
void delay_us(unsigned int us)
{
// Convert microseconds us into how many clock ticks it will take
us *= SYS_FREQ / 1000000 / 2; // Core Timer updates every 2 ticks
_CP0_SET_COUNT(0); // Set Core Timer count to 0
while (us > _CP0_GET_COUNT()); // Wait until Core Timer count reaches the number we calculated earlier
}
void delay_ms(int ms)
{
delay_us(ms * 1000);
}
// Initialise peripheral UART 6
void UART_Init()
{
int pbClk;
pbClk = SYS_FREQ / 2; // Our PBCLK2 divider was set to 1, so PBCLK2 is exactly half the speed of the system clock, or 100Mhz
U6MODE = 0; // Set UART 6 off prior to setting it up
U6MODEbits.BRGH = 0; // We want standard speed mode. Not necessary as we just set U6MODE to 0 so this is just for explanation's sake
U6BRG = pbClk / (16 * 38400) - 1;// This is the formula straight from the datasheet
U6STA = 0; // Disable the TX and RX pins, clear all flags
U6STAbits.UTXEN = 1; // Enable the TX pin
U6STAbits.URXEN = 1; // Enable the RX pin
U6MODEbits.PDSEL = 0; // PDSEL controls how many data bits and how many parity bits we want, this is the default of 8-bit data, no parity bits that most terminals use
U6MODEbits.STSEL = 0; // STSEL controls how many stop bits we use, let's use the default of 1
U6MODEbits.ON = 1; // Turn on the UART 6 peripheral
}
// Overwrite _mon_putc() to enable us to use printf
void _mon_putc (char c)
{
while (U6STAbits.UTXBF); // Wait til current transmission is complete
U6TXREG = c;
}
/*
*
*/
int main() {
// Set up all ports to be digital and not analog
ANSELA = 0;
ANSELB = 0;
ANSELC = 0;
ANSELD = 0;
ANSELE = 0;
ANSELF = 0;
ANSELG = 0;
ANSELH = 0;
ANSELJ = 0;
// Initialise peripheral UART 6
UART_Init();
// Set up PPS for UART 6
U6RXR = 0b1100; // RC2 = U6RX
RPD4R = 0b0100; // RD4 = U6TX
TRISCbits.TRISC2 = 1; // Make RC2 (U6RX) an input
TRISDbits.TRISD4 = 0; // Make RD4 (U6TX) an output
char buf[100] = {};
// master
SPI2CONbits.ON = 0; // Turn off SPI2 before configuring
SPI2CONbits.MSTEN = 1; // master mode
SPI2CONbits.CKP = 1; // Clock signal is active low, idle state is high
SPI2CONbits.CKE = 0; // Data is shifted out/in on transition from idle (high) state to active (low) state
SPI2CONbits.SMP = 1; // Input data is sampled at the end of the clock signal
SPI2CONbits.MODE32 = 0; // use 16 bit mode
SPI2CONbits.MODE16 = 1;
//SPI2BUF; // clear rx buffer by reading it
SPI2BRG = 0x06; // baud rate to 8 MHz
SPI2CONbits.ENHBUF = 0; // Disables Enhanced Buffer mode [also discussed below]
//SPI2STATbits.SPIROV = 0; // clear overflow bit
SPI2CONbits.ON = 1; // turn on master
// slave
SPI1BUF; // clear the buffer
SPI1CONbits.ON = 0; // Turn off SPI1 before configuring
SPI1CONbits.MSTEN = 0; // save mode
SPI1CONbits.MODE32 = 0; // use 16 bit mode
SPI1CONbits.MODE16 = 1;
SPI1STATbits.SPIROV = 0; // clear the overflow
SPI1CONbits.ON = 1; // turn on slave, slave mode do not set baud rate
// Set up PPS for SPI2 on RD7 and RB5
SDI2R = 0b1110; // RD7 = SDI2
RPB5R = 0b0110; // RB5 = SDO2
TRISDbits.TRISD7 = 1; // Set RD7 as input because it's SDI2
// Set up PPS for SPI1
SDI1R = 0b1101; // RA14 = SDI1
RPD10R = 0b0101; // RD10 = SDO1
TRISAbits.TRISA14 = 1; // Set RA14 as input because it's SDI1
int count = 0;
while(1){
unsigned short master = 0, slave = 0;
unsigned short rmaster = 0, rslave = 0;
master += count;
slave += count;
printf("beginning master and slave SPI communication.\n");
// have the slave write its data to its SPI buffer, data will not be sent until master performs a write
SPI1BUF = slave;
// have master perform a write
SPI2BUF = master;
// wait until data is received
while(!SPI2STATbits.SPIRBF){ } // master
//while(!SPI1STATbits.SPIRBF){ } // slave
// receive the data
rmaster = SPI2BUF;
rslave = SPI1BUF;
sprintf(buf, "Master sent 0x%04x, Slave sent 0x%04x\r\n", master, slave);
printf(buf);
sprintf(buf, "Slave read 0x%04x, Master read 0x%04x\r\n", rslave, rmaster);
printf(buf);
count++;
}
return (EXIT_SUCCESS);
}
Aidan Author
Hi Adan,
I'm sorry I didn't got to see this comment until now because for some reason it got marked as spam by disqus and never showed up.
I'm glad you got it working.
Adan
Hey Aidan,
I'm working with this eeprom by microchip on a breadboard via SPI and got it working with Arduino rather quickly. I translated the code to the PIC32mz and feel quite confident that I programmed the logic correctly (according to the datasheet and thanks to your help with this blog). Also, I believe I have connected the pins between the starter kit and breadboard properly.
On Arduino it worked when setting 2MHz and Mode 0. Arduino config is something like this -> SPISettings spiSetting(2000000, MSBFIRST, SPI_MODE0); Since I know there's data saved on the EEPROM, my first goal is to just read what I wrote with my Arduino.
I think I understand most of SPI with the PIC32; however the biggest hurdle I'm finding is understanding all the SPI configuration bits. Would you take a look at the configuration and let me know if this looks okay or if I need to add anything. I can send my code if needed.
Also, once I get this working I will happily share my code with you via Github so you can post on your blog for other people that might use this EEPROM as it appears to be an extremely popular choice.
Thanks again for your help not only on this example, but I've learned a lot from your other posts. Keep up the great work as this blog has been one of my main resources in becoming familiar with the Pic32!
SPI1CONbits.ON = 0; // turn off SPI1 before configuringSPI1CONbits.MODE32 = 0; // use 8 bit mode
SPI1CONbits.MODE16 = 0; // use 8 bit mode
SPI1CONbits.MSTEN = 1; // make master
SPI1CONbits.CKP = 0; // using SPI mode 0 - CPOL = 0
SPI1CONbits.CKE = 1; // using SPI mode 0 - CPHA = 0
SPI1CONbits.SMP = 1; // input data is sampled at the end of the clock signal
SPI1BRG = 49; // 2 MHz - divided from clock frequency of 200MHz
SPI1CONbits.ON = 1; // turn on SPI1
Aidan Author
Hi Adan,
I'm glad to hear the site has been useful. It was a struggle to get this far and the microchip forums are often filled with unhelpful people.
I have used a few flash memories with my PIC32MZ, and I used the following settings:
SPI1CONbits.CKP = 0; // Clock signal is active low, idle state is highSPI1CONbits.CKE = 1; // Data is shifted out/in on transition from idle (high) state to active (low) state
SPI1CONbits.SMP = 0; // Input data is sampled at the end of the clock signal
SPI1CONbits.MODE16 = 0; // Do not use 16-bit mode
SPI1CONbits.MODE32 = 0; // Do not use 32-bit mode (combines with the above line to activate 8-bit mode)
SPI1BRG = 0; // Set Baud Rate Generator to 0 [discussed below]
SPI1CONbits.ENHBUF = 0; // Disables Enhanced Buffer mode [also discussed below]
In other words, the same as you have except I had to set SMP to 0. I never got around to finding out why it worked like that (and to be honest once it worked I forgot about it) but the project I used it for is working fine and has been for a few months :)
I hope this helps!
Adan
Got it working and posted here.
It was mainly a timing issue not waiting for SPI buffer to receive data. Feel free to use, thanks again!
Aidan Author
Excellent, so it was working after all. Nice job!
Edit: I read your github stuff, thanks for mentioning this blog and good work on the code. When I get some free time I plan to write about EEPROMs (well, flash memories in general). Thanks again.
Adan
It was an issue I had with the chip select, but fixed it. Thanks
Aidan Author
Good news and glad it's working now.
Blom
Hi Aidan,
I want to implement SPI4 for my PIC32MZ064EFH2048.
The only thing that I want to a integer value to digital potentiometer once.
I don't know why, but the dig potentiometer is not receiving the value.
SCK4= RD10
RB4 is SS slaveselect.
// PIC32MZ2048EFH064 Configuration Bit Settings
// 'C' source line config statements
// DEVCFG3
#pragma config USERID = 0xFFFF // Enter Hexadecimal value (Enter Hexadecimal value)
#pragma config FMIIEN = ON // Ethernet RMII/MII Enable (MII Enabled)
#pragma config FETHIO = ON // Ethernet I/O Pin Select (Default Ethernet I/O)
#pragma config PGL1WAY = OFF // Permission Group Lock One Way Configuration (Allow only one reconfiguration)
#pragma config PMDL1WAY = OFF // Peripheral Module Disable Configuration (Allow only one reconfiguration)
#pragma config IOL1WAY = OFF // Peripheral Pin Select Configuration (Allow only one reconfiguration)
#pragma config FUSBIDIO = OFF // USB USBID Selection (Controlled by the USB Module)
// DEVCFG2
#pragma config FPLLIDIV = DIV_1 // System PLL Input Divider (8x Divider)
#pragma config FPLLRNG = RANGE_5_10_MHZ// System PLL Input Range (34-68 MHz Input)
#pragma config FPLLICLK = PLL_FRC // System PLL Input Clock Selection (FRC is input to the System PLL)
#pragma config FPLLMULT = MUL_50 // System PLL Multiplier (PLL Multiply by 128)
#pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider (32x Divider)
#pragma config UPLLFSEL = FREQ_24MHZ // USB PLL Input Frequency Selection (USB PLL input is 24 MHz)
// DEVCFG1
#pragma config FNOSC = SPLL // Oscillator Selection Bits (Fast RC Osc w/Div-by-N (FRCDIV))
#pragma config DMTINTV = WIN_127_128 // DMT Count Window Interval (Window/Interval value is 127/128 counter value)
#pragma config FSOSCEN = OFF // Secondary Oscillator Enable (Enable SOSC)
#pragma config IESO = ON // Internal/External Switch Over (Enabled)
#pragma config POSCMOD = OFF // Primary Oscillator Configuration (Primary osc disabled)
#pragma config OSCIOFNC = OFF // CLKO Output Signal Active on the OSCO Pin (Disabled)
#pragma config FCKSM = CSECME // Clock Switching and Monitor Selection (Clock Switch Enabled, FSCM Enabled)
#pragma config WDTPS = PS1048576 // Watchdog Timer Postscaler (1:1048576)
#pragma config WDTSPGM = STOP // Watchdog Timer Stop During Flash Programming (WDT stops during Flash programming)
#pragma config WINDIS = NORMAL // Watchdog Timer Window Mode (Watchdog Timer is in non-Window mode)
#pragma config FWDTEN = OFF // Watchdog Timer Enable (WDT Enabled)
#pragma config FWDTWINSZ = WINSZ_25 // Watchdog Timer Window Size (Window size is 25%)
#pragma config DMTCNT = DMT31 // Deadman Timer Count Selection (2^31 (2147483648))
#pragma config FDMTEN = OFF // Deadman Timer Enable (Deadman Timer is enabled)
// DEVCFG0
#pragma config DEBUG = OFF // Background Debugger Enable (Debugger is disabled)
#pragma config JTAGEN = OFF // JTAG Enable (JTAG Port Enabled)
#pragma config ICESEL = ICS_PGx1 // ICE/ICD Comm Channel Select (Communicate on PGEC1/PGED1)
#pragma config TRCEN = OFF // Trace Enable (Trace features in the CPU are enabled)
#pragma config BOOTISA = MIPS32 // Boot ISA Selection (Boot code and Exception code is MIPS32)
#pragma config FECCCON = OFF_UNLOCKED // Dynamic Flash ECC Configuration (ECC and Dynamic ECC are disabled (ECCCON bits are writable))
#pragma config FSLEEP = OFF // Flash Sleep Mode (Flash is powered down when the device is in Sleep mode)
#pragma config DBGPER = PG_ALL // Debug Mode CPU Access Permission (Allow CPU access to all permission regions)
#pragma config SMCLR = MCLR_NORM // Soft Master Clear Enable bit (MCLR pin generates a normal system Reset)
#pragma config SOSCGAIN = GAIN_2X // Secondary Oscillator Gain Control bits (2x gain setting)
#pragma config SOSCBOOST = OFF // Secondary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
#pragma config POSCGAIN = GAIN_2X // Primary Oscillator Gain Control bits (2x gain setting)
#pragma config POSCBOOST = OFF // Primary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
#pragma config EJTAGBEN = NORMAL // EJTAG Boot (Normal EJTAG functionality)
// DEVCP0
#pragma config CP = OFF // Code Protect (Protection Disabled)
// SEQ3
#pragma config TSEQ = 0xFFFF // Boot Flash True Sequence Number (Enter Hexadecimal value)
#pragma config CSEQ = 0xFFFF // Boot Flash Complement Sequence Number (Enter Hexadecimal value)
// #pragma config statements should precede project file includes.
// Use project enums instead of #define for ON and OFF.
/*
* File: main.c
* Author:
*
* Created on February 1, 2019, 12:36 PM
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <xc.h>
#define SYS_FREQ 200000000
void set_performance_mode()
{
unsigned int cp0;
// Unlock Sequence
asm volatile("di"); // Disable all interrupts
SYSKEY = 0xAA996655;
SYSKEY = 0x556699AA;
// PB1DIV
// Peripheral Bus 1 cannot be turned off, so there's no need to turn it on
PB1DIVbits.PBDIV = 1; // Peripheral Bus 1 Clock Divisor Control (PBCLK1 is SYSCLK divided by 2)
// PB2DIV
PB2DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
PB2DIVbits.PBDIV = 1; // Peripheral Bus 2 Clock Divisor Control (PBCLK2 is SYSCLK divided by 2)
// PB3DIV
PB3DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
PB3DIVbits.PBDIV = 1; // Peripheral Bus 3 Clock Divisor Control (PBCLK3 is SYSCLK divided by 2)
// PB4DIV
PB4DIVbits.ON = 1; // Peripheral Bus 4 Output Clock Enable (Output clock is enabled)
while (!PB4DIVbits.PBDIVRDY); // Wait until it is ready to write to
PB4DIVbits.PBDIV = 0; // Peripheral Bus 4 Clock Divisor Control (PBCLK4 is SYSCLK divided by 1)
// PB5DIV
PB5DIVbits.ON = 1; // Peripheral Bus 5 Output Clock Enable (Output clock is enabled)
PB5DIVbits.PBDIV = 1; // Peripheral Bus 5 Clock Divisor Control (PBCLK5 is SYSCLK divided by 2)
// PB7DIV
PB7DIVbits.ON = 1; // Peripheral Bus 7 Output Clock Enable (Output clock is enabled)
PB7DIVbits.PBDIV = 0; // Peripheral Bus 7 Clock Divisor Control (PBCLK7 is SYSCLK divided by 1)
// PB8DIV
PB8DIVbits.ON = 1; // Peripheral Bus 8 Output Clock Enable (Output clock is enabled)
PB8DIVbits.PBDIV = 1; // Peripheral Bus 8 Clock Divisor Control (PBCLK8 is SYSCLK divided by 2)
// PRECON - Set up prefetch
PRECONbits.PFMSECEN = 0; // Flash SEC Interrupt Enable (Do not generate an interrupt when the PFMSEC bit is set)
PRECONbits.PREFEN = 0b11; // Predictive Prefetch Enable (Enable predictive prefetch for any address)
PRECONbits.PFMWS = 0b010; // PFM Access Time Defined in Terms of SYSCLK Wait States (Two wait states)
// Set up caching
cp0 = _mfc0(16, 0);
cp0 &= ~0x07;
cp0 |= 0b011; // K0 = Cacheable, non-coherent, write-back, write allocate
_mtc0(16, 0, cp0);
// Lock Sequence
SYSKEY = 0x33333333;
asm volatile("ei"); // Enable all interrupts
}
void delay_us(unsigned int us)
{
// Convert microseconds us into how many clock ticks it will take
us *= SYS_FREQ / 1000000 / 2; // Core Timer updates every 2 ticks
_CP0_SET_COUNT(0); // Set Core Timer count to 0
while (us > _CP0_GET_COUNT()); // Wait until Core Timer count reaches the number we calculated earlier
}
void delay_ms(int ms)
{
delay_us(ms * 1000);
}
void UART_Init(){
int pbClk;
pbClk = SYS_FREQ / 2; // Our PBCLK2 divider was set to 1, so PBCLK2 is exactly half the speed of the system clock, or 100Mhz
//100
U4MODE = 0; // Set UART 5 off prior to setting it up
U4MODEbits.BRGH = 0; // We want standard speed mode. Not necessary as we just set U5MODE to 0 so this is just for explanation's sake
U4BRG = pbClk / (16 * 115200) - 1;// This is the formula straight from the datasheet
U4STA = 0; // Disable the TX and RX pins, clear all flags
U4STAbits.UTXEN = 1; // Enable the TX pin
U4STAbits.URXEN = 1; // Enable the RX pin
U4MODEbits.PDSEL = 0; // PDSEL controls how many data bits and how many parity bits we want, this is the default of 8-bit data, no parity bits that most terminals use
U4MODEbits.STSEL = 0; // STSEL controls how many stop bits we use, let's use the default of 1
U4MODEbits.ON = 1; // Turn on the UART 5 peripheral
}
void _mon_putc (char c)
{
while (U4STAbits.UTXBF); // Wait til current transmission is complete
U4TXREG = c;
}
void SPI_init()
{
SPI4CONbits.ON = 0; // Turn off SPI2 before configuring
SPI4CONbits.MSTEN = 1; // Enable Master mode
SPI4CONbits.CKP = 1; // Clock signal is active low, idle state is high
SPI4CONbits.CKE = 0; // Data is shifted out/in on transition from idle (high) state to active (low) state
SPI4CONbits.SMP = 1; // Input data is sampled at the end of the clock signal
SPI4CONbits.MODE16 = 0; // Do not use 16-bit mode
SPI4CONbits.MODE32 = 0; // Do not use 32-bit mode (combines with the above line to activate 8-bit mode)
SPI4BRG = 0; // Set Baud Rate Generator to 0 [discussed below]
SPI4CONbits.ENHBUF = 0; // Disables Enhanced Buffer mode [also discussed below]
SPI4CONbits.ON = 1; // Configuration is done, turn on SPI2 peripheral
}
/*
int SPI_send(int data)
{
// data = 245;
SPI4BUF = data; // Send *data* to SPI2BUF.
while (SPI4STATbits.SPIRBE); // Which the receive buffer is empty, loop
return (int)SPI4BUF; // Return whatever is in SPI2BUF
}
*/
void setup(){
//Deze functie moet 1x worden doorlopen
// Set up all ports to be digital and not analog
ANSELB = 0;
ANSELG = 0;
// Set outputs en inputs (8 NAAR TEL)
TRISBbits.TRISB12=1; //DRAIN BOVEN g7 1.2
TRISBbits.TRISB13=1; //DRAIN BENEDEN g8 1.3
TRISBbits.TRISB5=0; //TOGGLE GEPROGRAMMEERDE CLOCK 1.4
TRISBbits.TRISB7=0; //SCANDISABLE BENEDEN (was rb5) 1.9
TRISBbits.TRISB8=0; //RODE LED HEARTBEAT was rb4 1.10
TRISBbits.TRISB3=0; //SCANDISABLE 1.7
TRISBbits.TRISB6=0; //LED ORANJE OBJECT 1.8
TRISBbits.TRISB9=1; //TELLER is doorgesoldeerd aan RB10 1.11
TRISBbits.TRISB2=0; //Orange programmable LED kaart
TRISBbits.TRISB4=0; //CS
LATBbits.LATB3=1;
LATBbits.LATB7=1;
LATBbits.LATB3=0;
LATBbits.LATB7=0;
LATBbits.LATB6=0;
return;
}
void spidat(){
int resistorValue = 245, adress = 0;
// have the slave write its data to its SPI buffer, data will not be sent until master performs a write
//SPI1BUF = slave;
// have master perform a write
LATBbits.LATB4=0;
delay_us(100000);
SPI4BUF = adress;
SPI4BUF = resistorValue;
delay_us(100000);
LATBbits.LATB4=1;
// wait until data is received
while(!SPI4STATbits.SPIRBF){ }
return;
}
void main(){
setup();
// Set max performance mode
set_performance_mode();
// Set up PPS for UART 5 OUD
//U5RXR = 0b0100; // RPRF1 = U5RX
// RPD3R = 0b0011; // RPD3 = U5TX
// TRISFbits.TRISF1 = 1; // Make RF1 an input
// TRISDbits.TRISD3 = 0; // Make RD3 an output
//Setup PPS for UART 4 NIEUW
U4RXR = 0b0010;
RPG6R = 0b0010;
TRISBbits.TRISB14 = 1;
TRISGbits.TRISG6 = 0;
// SPI4 NIEUW
SDI4R = 0b0001; // RPG7 = SDI4
RPG9R = 0b1000; // RG9 = SDO4
TRISGbits.TRISG7 = 1; // Set RB3 as input because it's SDI2
// Initialise peripheral UART 5
UART_Init();
SPI_init();
spidat();
while(1){
..........
}
Aidan Author
Hi again Blom,
With the digital potentiometer, do you have to send it an address and then a value? And then what data does it return to you?
Anyway, we have to change your spidat() function a bit:
void spidat(){
int resistorValue = 245, adress = 0;
// have the slave write its data to its SPI buffer, data will not be sent until master performs a write
//SPI1BUF = slave;
// have master perform a write
LATBbits.LATB4=0;
delay_us(100000);
SPI4BUF = adress;
// We have to wait for it to finish sending and a reply to be received before sending the next byte because we are not using enhanced buffers mode. When a byte is received, SPI Receive Buffer Empty will be false
while (SPI4STATbits.SPIRBE);
// Write next value and wait for reply
SPI4BUF = resistorValue;
while (SPI4STATbits.SPIRBE);
delay_us(100000);
// If you to get a reply after this, you have to do this next:
SPI4BUF = 0xFF;
while (SPI4STATbits.SPIRBE);
// Now the reply will be in SPI4BUF and you can read it
// Only set slave select to one when SPI transaction is finished, not before waiting for data
LATBbits.LATB4=1;
return;
}
Blom
Hi Aidan thnx again, it is working now :)
I am working with a AD8400, 1 channel 1kohm version.
you need to send a adress, but the one I use has only one wiper so one adress, equal to zero.
Don't no for sure if it neccesary with the 1 channel.
After that you need to send a value 0-255 to change the wiper.
But it is working different when is send a value with the Arduino to the dig potentiometer.
Arduino was: 255 is low resistance and 0 is high resistance
PIC is: 255 is high resistance and 0 is low resistance
Very strange and I didn't change any electrical because I designed it on PCB.
Aidan Author
Hi Blom,
It is probably necessary, a lot of ICs have the same "protocol" across many different versions and they just ignore the incoming value, but they still wait to receive it. Check the datasheet to be sure. I cannot imagine why the value would be backwards if you haven't changed the wiring at all. That's quite strange. I'm glad it's working though.
Blom
Hi Aidan,
I think it is also necessary for the 1 channel even it has only one address.
Still didn't figured out why it is acting backwards though..
Blom
Would love to see something about setting up Ethernet with LAN8710a on a PIC32MZ and CAN bus.
What are your projects at the moment? =)
Aidan Author
Hi Blom,
Unfortunately I don't have any plans to do the ethernet stuff at the moment, I'm using an esp32 to connect to the pic32 via wifi for my networking needs.
I'm currently working on getting the SQI peripheral to work with an external 8MB PSRAM, almost done with it.
I will get around to ethernet and CAN eventually but I have other stuff to do before that :)
Blom
Hi Aidan,
Alright that sounds like an interesting project to ;)!
Maybe I am going to deep myself into the PIC32MZ in combination with the LAN8710a.
I saw some pictures of your dev board, looks pretty cool that you are making your own to. =)
Well if you decide you are not going to do anything with Ethernet and CAN..
I still will be waiting patiently for other cool stuff around this site!
Cheers!
Konstantin Dimitrov
Actually, there is a port of PLIB for MZ:
https://github.com/knivd/PL...
Comments are hosted by Disqus, which loads only when you ask for it.