0
\$\begingroup\$

I am working with an ATmega32-A microcontroller. Using USART communication, I am displaying data on monitor and am using switch case to select different commands. In one of the commands I have written the following code:

 case(DATA):

  init_io();
  statusreg = AD7798_8(0x40, 0xFF); 
  printf("status register %02x\r\n", statusreg); 

  if (statusreg != 0x80) 
      printf("unexpected power on status %02x\r\n", statusreg); 

  while(1){
            while ((statusreg & 0x80) != 0);                 // wait till ADC is ready 
            adc = AD7798_16(0x58, 0xFFFF);                   // read register 
            printf("ADC value is %04x\r\n", adc); 
          } 
  Command=0;
  break;

But the above code is printing the ADC value infinite times. I have changed the while loop to the following

   while(1){
            while ((statusreg & 0x80) != 0);                 // wait till ADC is ready 
            adc = AD7798_16(0x58, 0xFFFF);                   // read register 
            printf("ADC value is %04x\r\n", adc); 
          } 

After that it is printing only once, but does not accept any more commands. I have to re-build if I want to enter any other command. Any help appreciated.

\$\endgroup\$
1
  • 4
    \$\begingroup\$ Am I the only person who can't see any difference between the two while(1) loops? Also, the inner while loop will execute either 0 or an infinite number of iterations, depending on the value in statusreg coming into it. This is the same problem we addressed here. \$\endgroup\$
    – Dave Tweed
    Commented Oct 17, 2012 at 15:44

1 Answer 1

6
\$\begingroup\$

A while(1){} loop never exits, (unless you have a break inside) so it will always stick there. Why do you need the while(1) anyway? It looks like you are only reading once from the ADC.
If you do want to loop more than once, you need to add a condition to equal 0 when whatever it is you want to do inside has finished.

\$\endgroup\$
2
  • \$\begingroup\$ Ha, ignore my last comment, I misread all the text. \$\endgroup\$
    – Kortuk
    Commented Oct 17, 2012 at 14:23
  • \$\begingroup\$ The while(1) looks entirely unnecessary anyways since it's going to lock up until the ADC is available. It's not like he's timing out and retrying things. \$\endgroup\$ Commented Oct 17, 2012 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.