PIC32 SPI

Blank

spiinit spi1
spi2
spiread
spiwrite

SPI is a strange interface in that something always comes out when something is put in so reading and writing can in theory occur at the same time.

spiinit 
spiinit <channel> <speed>
spiinit 1 100000
spiinit 2 20000000

There are two spi channels on the BV513 (PIC32) and these are designated 1 and 2. Channel 2 is used (dedicated) for the SD Card and the routines that use the SD Card will alter the speed to 20MHz if the card is mounted. In addition to this they may alter the spi parameters. Normally this is okay and in fact has been tested with other peripherals that seem to work fine, however to be on the safe side channel 1 may be preferred.

The speed has a range of 100k to 20MHz that must be entered in Hz, see the examples above. There are many settings on an spi device, clock polarity etc. which will be set to the normal default with this setting. The actual value for the SPIxCON register (PIC32) is:

SPIxCON = 0x8120

For other settings of this register (substitute the ‘x’ for either 1 or 2) can be directly modified with the ‘pokei’ keyword.

spi1, spi2
spi1(byte-value)
a=spi1(0xff)
b=spi1(value)

This keyword will read and write the spi bus at the same time. To write a byte to the spi bus, call this with the required byte value e.g. to write:

spi2(0x27)

This will write 0x27 to the spi2 bus. Remember that all spi devices also need a chip select, this does not do that. To read a byte from the spi bus:

a=spi1(0xff)

The convention is to write 0xff and collect what comes out of the back end so to speak. In this case ‘a’ will contain the recovered data.

spiread, spiwrite
spiread channel, buffer, length
spiread 1 x% 20
spiread 2 adr(a$) 128

For devices where a block of data is required this keyword can be used, it will be faster than using spix() in a loop. The buffer must be an area of RAM that the word can fill. This will normally be obtained by using the ‘adr’ keyword of an existing variable or by actually specifying an area of user RAM. Channel is the spi channel either 1 or 2.

The ‘spiwrite’ keyword operates in exactly the same way but instead of filling the buffer it writes the contents of the buffer to the spi bus.