#include "pic24_all.h"
#include <stdio.h>
#define CONFIG_SLAVE_ENABLE() CONFIG_RB2_AS_DIG_OUTPUT()
#define SLAVE_ENABLE() _LATB2 = 0 //low true assertion
#define SLAVE_DISABLE() _LATB2 = 1
void configSPI1(void) {
SPI1CON1 =
#if (defined(__dsPIC33E__) || defined(__PIC24E__))
//spi clock = 60MHz/1*6 = 60MHz/4 = 10MHz
PRI_PRESCAL_1_1 | //1:1 primary prescale
SEC_PRESCAL_6_1 | //6:1 secondary prescale
#else
//spi clock = 40MHz/4*1 = 40MHz/4 = 10MHz
PRI_PRESCAL_4_1 | //4:1 primary prescale
SEC_PRESCAL_1_1 | //1:1 secondary prescale
#endif
CLK_POL_ACTIVE_HIGH | //clock active high (CKP = 0)
SPI_CKE_ON | //out changes active to inactive (CKE=1)
SPI_MODE8_ON | //8-bit mode
MASTER_ENABLE_ON; //master mode
SPI1STATbits.SPIEN = 1; //enable SPI mode
//configure pins. Only need SDO, SCLK since POT is output only
#if (defined(__dsPIC33E__) || defined(__PIC24E__))
//nothing to do here. On this family, the SPI1 port uses dedicated
//pins for higher speed. The SPI2 port can be used with remappable pins.
//you may need to add code to disable analog functionality if the SPI ports
//are on analog-capable pins.
#else
//all other families (PIC24H/PIC24F/dsPIC33F)
CONFIG_SDO1_TO_RP(RB6_RP); //use RB6 for SDO
CONFIG_RB6_AS_DIG_OUTPUT(); //Ensure that this is a digital output
CONFIG_SCK1OUT_TO_RP(RB7_RP); //use RB7 for SCLK
CONFIG_RB7_AS_DIG_INPUT(); //Ensure that this is a digital input
#endif
CONFIG_SLAVE_ENABLE(); //chip select for MCP41xxx
SLAVE_DISABLE(); //disable the chip select
}
void setPotWiper(uint8_t u8_i) {
SLAVE_ENABLE(); //assert MCP41xxx chipselect
ioMasterSPI1(0x11); //command byte to select wiper register
ioMasterSPI1(u8_i);
SLAVE_DISABLE(); //negate MCP41xxx chipselect
}
#define BUFSIZE 15
char sz_1[BUFSIZE+1];
int main (void) {
uint16_t u16_pv;
configBasic(HELLO_MSG);
configSPI1();
while (1) {
outString("Input decimal value (0-255): ");
inString(sz_1,BUFSIZE);
sscanf(sz_1,"%d", (int *) &u16_pv);
printf("\nSending %d to pot.\n",u16_pv);
setPotWiper(u16_pv & 0x00FF);
}
}