bug? or am i wrong?

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

hello,
i'm learning C from the book from smileymicros.
it's getting along, but now i have an error i can't figure out.

this is the code (partial)
//*******************************************
int ADC_read(void)
{
char i;
int ADC_temp = 0;
int ADCr = 0;
// do a dummy read first
ADCSRA |= (1<<ADSC); // do a single conversion

// wait for conversion done
while (!(ADCSRA && 0x40));

// do the ADC conversion 8 times
for (i=0; i<8; i++)
{
ADCSRA |= (1<<ADSC);
while (!(ADCSRA && 0x40));

ADC_temp = ADCL; // read out ADCL register
ADC_temp += (ADCH << 8 ); // read out ADCH register

//accumulate for later averaging
ADCr += ADC_temp;
}

sendChar('B'); //*************ERROR

ADCr = ADCr >> 3; //average the 8 samples
ADCSRA = (0<<ADEN); //disable the ADC

return ADCr;
}

// routine 2***********************************
void getAbs()
{
int ADCresult = 0;
char abso[] = {'0','0','0','\0'};
ADC_init(7);
ADCresult = ADC_read();
// sendChar(ADCresult);
itoa(ADCresult, abso, 10);

sendString ("\r the value is: ");
sendString (abso);
}

//end code***********************************

the routine getAbs() calls ADC_read
how it is posted it works, but if i delete the line
sendChar('B'); //*************ERROR
the ADC_read function always returns 0 ????

if i use sendChar(ADCr) instead of ('B') i get the correct value from the ADC, but the function returns 0 :-(

So far i found al the errors (until page 217, not bad?) but i don't get it now.
Please help???
I've used the WINAVR 20050214 & and 200404 (as recomended by smileymicros)

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
 while (!(ADCSRA && 0x40)); 

This is incorrect, since it will not wait for the conversion to complete. Try:

 while (ADCSRA & (1 << ADSC)) /*EMPTY*/; 

This would explain getting 0-s back from the ADC, but not why
calling sendChar() -- presumably introducing a delay, but only after you're
finished the conversions -- would "fix" the problem.

Anyway, fix this line (both places) and see if it looks different.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

thanks, this solves the problem.
The delay invoked by sendChar was indeed the reason it worked, because a

_delay_loop_1(20);

worked also...

Still don't know why this delay then solved the problem...