
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 mikroPascal 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
var value : word;
procedure InitMain();
begin
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;
// DAC increments (0..4095) --> output voltage (0..Vref)
procedure DAC_Output(valueDAC : word) ;
begin
while (SPI2STAT.1 = 1) do // wait for SPI module to finish, if doing something
nop;
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) do // Wait for SPI module to finish write
nop;
LATC.CS_PIN := 1; // CS disable for DAC
end;
begin
InitMain();
while 1 = 1 do
begin
value := 1;
while value < $FFF do
begin
DAC_Output(value);
Delay_ms(5);
value := value+1;
end;
end; // the output in the mid-range
end.