In the master mode, the clock provided to the SPI module is the instruction cycle TCY . This clock will then be prescaled by the primary prescaler, specified by PPRE<1:0> (SPIxCON<1:0>), and the secondary prescaler, specified by SPRE<2:0> (SPIxCON<4:2>). The prescaled instruction clock becomes the serial clock and is provided to external devices via the SCKx pin.
FCY = 30 MHZ | SECONDARY PRESCALER SETTINGS | |||||
---|---|---|---|---|---|---|
1:1 | 2:1 | 4:1 | 6:1 | 8:1 | ||
Primary prescaler settings | ||||||
1:1 | 30 000 | 15 000 | 7 500 | 5 000 | 3 750 | |
4:1 | 7 500 | 3 750 | 1 875 | 1 250 | 938 | |
16:1 | 1 875 | 938 | 469 | 313 | 234 | |
64:1 | 469 | 234 | 117 | 78 | 59 | |
Fcy = 5 Mhz | ||||||
Primary prescaler settings | ||||||
1:1 | 5 000 | 2 500 | 1 250 | 833 | 625 | |
4:1 | 1 250 | 625 | 313 | 208 | 156 | |
16:1 | 313 | 156 | 78 | 52 | 39 | |
64:1 | 78 | 39 | 20 | 13 | 10 |
NOTE: SCKx clock frequencies shown in kHz. All frequencies are not supported; electrical characteristics of individual microcontrollers of dsPIC30F family should be consulted.
const char CS_PIN = 0; unsigned int value; void InitMain() { ADPCFG = 0xFFFF; // Set AN pins as digital Spi_Init(); // Initialize SPI module TRISF.CS_PIN = 0; // Set CS pin as output }//~ // DAC increments (0..4095) --> output voltage (0..Vref) void DAC_Output(unsigned int valueDAC) { char temp; PORTF.CS_PIN = 0; // Select DAC module // Send 2 bytes of valueDAC variable temp = (valueDAC >> 8) & 0x0F; // Prepare hi-byte for transfer // It's a 12-bit number, so only // lower nibble of high byte is used temp |= 0x30; // Set MCP4921 control bits Spi_Write(temp); // Send data via SPI temp = valueDAC; // Prepare lo-byte for transfer Spi_Write(temp); // Send data via SPI PORTF.CS_PIN = 1; // Deselect DAC module }//~ void main() { InitMain(); value = 2047; // When program starts, DAC gives // the output in the mid-range while (1) { // Main loop DAC_Output(value++); if (value > 4095) value = 0; Delay_ms(10); } }//~!Function Spi2_Init initializes the SPI module in master mode 8-bit formatted, without the SS2 pin, sampling in the middle of the SPI cycle, prescale 1:8, and the clock FCY:1 low while waiting. If another format or communication speed is desired, the function Spi2_Init_Advanced instead of Spi2_Init should be used. The function Spi2_Data_Ready reads the value of the status bit SPIRBF (SPI2STAT<0>) and checks if there are data loaded into the receive buffer register. The function Spi2_Write transmits data via the SPI module. Data reception is performed by the function Spi2_Read. The SPI moduled is disabled by the function Spi2_Stop (clearing the control bit SPIEN), and the SPI module enable (setting the control bit SPIEN) is performed automatically by the function Spi2_Init or Spi2_Init_Advanced.