Problem with printing function return value

avrcmicrocontrollerprogramming

I am new to programming. I have small doubt, I know this is simple question but I am confused. I have the following function:

void ReadAdConfReg(void)
{              
    SPCR = 0x5D;
    ADC_CS = 0;      
    while (MISO_PIN != 0) ;
    spi(0x50);
    adcConfig = spi(0xFF);    
    adcConfig = (adcConfig << 8) | spi(0xFF);  
    ADC_CS = 1;    
}

I have declared adcConfig as global variable: unsigned int adcConfig.

How can I print the adcConfig value. Because this is a void function, it doesn't return any value.

I have tried like this:

ReadAdConfReg();
printf("configreg:%d",adcConfig);

Is it wrong? Or how can I print adcConfig value.

Controller is ATMega32A, compiler CodeVisionAVR.

Best Answer

If need the function to return a value it can't be declared void. As you have it now you have to call the function first, then pass the global variable into the printf function. So what you are doing should work.

To use the function with a return value, do something like this:

unsigned int ReadAdConfReg(void)
{        
    unsigned int retVal;
    SPCR = 0x5D;
    ADC_CS = 0;      
    while (MISO_PIN != 0) ;
    spi(0x50);
    adcConfig = spi(0xFF);    
    adcConfig = (adcConfig << 8) | spi(0xFF);  
    ADC_CS = 1;
    return acdConfig;    
}

(note - the previous edit used a local retVal, whilst leaving the adcConfig variable present which may have been confusing. You can pass the adcConfig directly as it's the correct type. If you want the function to be independent of the adcConfig though, use the local retVal instead in place of the adcConfig - this is probably better than using a global variable)

Then you can do:

printf("configreg:%d", ReadAdcConfigReg());