Hi all.
I have a strange issue and unable to come to a logical reason why my code is behaving strangely.
The code below updates the MCP 4921 DAC with the dac code incremented/decremented from a rotary encoder CCW or CW, when I turn clockwise the code increases, if I decrement the code decreases, so everything is fine here.
The problem
when I use the tracking variable dac_code_adj" it doesn't seem to "update" the DAC output, I have a LCD and the code is clearly displaying increase/decrease values as I turn the rotary encoder, Here is the strange part, if I use the same number as a hard-code the value, I can see the DAC output the voltage. I have no idea why its behaving this way.
volatile const int dac_fine_code_inc = 1;
volatile const int dac_course_code_inc = 50;
volatile const int dac_max = 2515;
volatile const int dac_min = 0;
volatile int dac_code_adj;
// Rotraty encoder will trigger CN for CCW OR CW
void __attribute__((__interrupt__,__auto_psv__)) _CNInterrupt(void)
{
/*
When a CN interrupt occurs, the user should read the PORT register associated with the CN
pin(s). This will clear the mismatch condition and set up the CN logic to detect the next pin
change. The current PORT value can be compared to the PORT read value obtained at the last
CN interrupt to determine the pin that changed.
The CN pins have a minimum input pulse-width specification. Refer to the ?Electrical
Characteristics? section of the specific device data sheet for further details.
*/
process_rotray_encoder();
rotray_ready = 1;
IFS1bits.CNIF = 0; // Clear flag for on change interrupt
}
int main(void)
{
init_system_setup();
while(1)
{
system_process();
}
return (EXIT_SUCCESS);
}
void system_process(void)
{
__delay_us(10);
// DAC SPI config + DAC code.
dac_write( 0x5, dac_code_adj );
// Display code.
unsigned char* buf[10];
itoa( buf, dac_code_adj, 10 );
}
void dac_write(unsigned short config, int data)
{
int result = (data | (config << 12));
CS_DAC = 0;
SPI1BUF = result;
while(!SPI1STATbits.SPIRBF);
CS_DAC = 1;
}
void process_rotray_encoder(void)
{
if( read_encoder() == DIR_CW)
{
dac_code_adj += dac_course_code_inc;
}
else if( read_encoder() == DIR_CCW )
{
dac_code_adj -= dac_course_code_inc;
}
if( dac_code_adj < dac_min )
{
dac_code_adj = dac_min;
}
else if ( dac_code_adj > dac_max)
{
dac_code_adj = dac_max;
}
}