NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » C Programming basic question

November 22, 2009
by FWSquatch
FWSquatch's Avatar

I need to take a reading from the analog to digital converter and use it set the length of an interval. I've grabbed the code from the tempsensor project and I understand how to use it to get the reading, but once I get the reading, I'm confused about how to program the rest in C. I want the reading to be able to set the interval variable to 8 different settings. I think I know how to write it out the long way, this is what I have now:

  if adc_read() > 896
    interval = 1;
    break
  if adc_read() <= 896
    if adc_read() <= 768
      if adc_read() <= 640
        if adc_read() <= 512
          if adc_read() <= 384
            if adc_read() <= 256
              if adc_read() <= 128
                interval = 8;
                break;
            interval = 7;
            break;
          interval = 6;
          break;
        interval = 5;
        break;
      interval = 4;
      break;
    interval = 3;
    break;
  interval = 2;
  break;

I'm thinking there has to be a better way. Is there? BTW, I have very little experience with C, so I'm not even sure if that code will work. I'm open to suggestions.

November 22, 2009
by mikedoug
mikedoug's Avatar

I'm guessing that you are wanting to set the interval based on ONE reading from the adc_read() function. From my memory, every time you call adc_read() it performs another read. If you are wanting to set this value based on ONE reading, then here's equivalent code:

x = adc_read();

if( x <= 128 )
  interval = 8;
else if( x <= 256 )
  interval = 7;
else if( x <= 384 )
  interval = 6;
else if( x <= 512 )
  interval = 5;
else if( x <= 640 )
  interval = 4;
else if( x <= 768 )
  interval = 3;
else if( x <= 896 )
  interval = 2; 
else
  interval = 1;

Unfortunately you can't do something like a switch/case to make it easier than this -- but changing to these if/else if branches gets rid of the massive nesting you had going on.

Let me know if that does work for you, or is not what you were going for.

MikeDoug

November 22, 2009
by FWSquatch
FWSquatch's Avatar

Thanks Mike. That's exactly what I was looking for. I'll give it a try.

Post a Reply

Please log in to post a reply.

Did you know that any circuit of voltage sources and resistors can be simplified to a "Thevenin" equivalent circuit? Learn more...