I also looked for some examples last week but couldn't find any. I am using PIC 16F884. This has MSSP so life is actually very easy. I have extracted some snippets of code from my application so you can see how it works. The deeply indented code is not runnable but intended to demonstrate how the subroutines are called. I hope this helps. It runs my apps fine but I can't guarantee that it is the most efficient.
I would be glad to explain if you need to contact me.
'SPI setup
pot_cs var PORTC.0 ' chip select
a2d_cs var PORTC.1 'chip select
amp_cs var PORTC.2 'chip select
SSPCON.5=1 'enable SSP
SSPCON.4=1 'Clock idles high bit name CKP
SSPCON.3=0 ' bit 3 to 0 indicate clock speed. bit 0 set means clock = OSC/16 = 1.25 MHz
SSPCON.2=0
SSPCON.1=0
SSPCON.0=1
SSPSTAT.7=1 ' SPI Master mode
SSPSTAT.6=0 ' data transmitted on rising edge of SCK
TRISC.3 = 0
TRISC.5 = 0
vcount var word
OUTPUT pot_cs
OUTPUT amp_cs
OUTPUT a2d_cs
' CODE TO CONTROL SPI POTENTIOMETER MicroChip MCP41050
valuebyte = 128 ' VALUE OF POT 0 TO 255
commandbyte = 17 ' bit 4 and 5 = command bits, bit 0 or 1 = channel select bit - 16 = write data, 1 = select CH0
pot_cs = 0
gosub sendspi
pot_cs = 1
'CODE TO CONTROL SPI AMPLIFIER MicroChip MCP6S21/2/6/8
valuebyte = 0 'set gain INDEX
commandbyte = 64 ' bit 5, 6 and 7 = command bits, bit 0 = register select - 0 = gain register, 1 = channel register
amp_cs = 0
gosub sendspi
amp_cs = 1
valuebyte = 0 ' select channel from input MUX
commandbyte = 65 ' bit 5, 6 and 7 = command bits, bit 0 = register select - 0 = gain register, 1 = channel register
amp_cs = 0
gosub sendspi
amp_cs = 1
' read SPI ADC MicroChip MCP3208
valuebyte = 0
commandbyte = 4 + 2 + channelnumber >> 2 ' SET BIT 2 HI FOR START BIT - bit 1 = single ended - bit 0 channelnumber may be 0 to 7
secondbyte = channelnumber << 6 'D1,D0 shifted to top bits
a2D_cs = 0
gosub txrxspi
a2D_cs = 1
end
sendspi:
SSPBUF = commandbyte
PAUSEUS 10
SSPBUF = valuebyte
PAUSEUS 7
return
txrxspi:
SSPBUF = commandbyte
PAUSEUS 10
SSPBUF = secondbyte
while SSPSTAT.0 = 0
'spin
WEND
vcount = (SSPBUF & 15) << 8
SSPBUF = valuebyte
while SSPSTAT.0 = 0
'spin
WEND
vcount = SSPBUF + vcount
return
end
Bookmarks