The example shows the initialization, writing, and reading data from the receive and transmit buffer register of an SPI module, respectively. The example shows the connection of the SPI2 module to the serial digital-to-analogue converter (DAC) MCP4921. The realization is carried out by using the mikroBasic compiler for dsPIC30F microcontrollers. Fig. 13-9 shows the electrical connection of the SPI module to the serial DAC MCP4921.
Fig. 13-9 Electrical connection of the SPI module to the serial DAC MCP4921.
program SPITest const LOAD_PIN = 2 ' DAC load pin const CS_PIN = 1 ' DAC CS pin dim value as word sub procedure InitMain() TRISC.LOAD_PIN = 0 ' LOAD pin TRISC.CS_PIN = 0 ' CS pin LATC.CS_PIN = 1 ' Set CS to inactive LATC.LOAD_PIN = 0 ' Set LOAD to inactive Spi2_Init_Advanced(_SPI_MASTER, _SPI_16_BIT, _SPI_PRESCALE_SEC_1, _SPI_PRESCALE_PRI_1, _SPI_SS_DISABLE, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_HIGH, _SPI_ACTIVE_2_IDLE) ' Init SPI end sub ' DAC increments (0..4095) --> output voltage (0..Vref) sub procedure DAC_Output(dim valueDAC as word) while (SPI2STAT.1 = 1) ' wait for SPI module to finish, if doing something nop wend LATC.CS_PIN = 0 ' CS enable for DAC SPI2BUF = 0x3000 or valueDAC ' Write CurrentValue to DAC (0x3 is required by DAC) while (SPI2STAT.1 = 1) ' Wait for SPI module to finish write nop wend LATC.CS_PIN = 1 ' CS disable for DAC end sub main: InitMain() while true value = 1 while value < $FFF DAC_Output(value) Delay_ms(5) value = value+1 wend wend ' the output in the mid-range end.