Search code examples
cloopsconceptual

using a loop to know when an "object goes past in c


This may be a basic question but I can't wrap my head around it, I am a newbie to c. Its a bit of a conceptual question so sorry. I am using a specific microprocessor but this is a question that was given in a tutorial which I never got the answer to.

I want to know how to code the following: A conveyor belt is running and passing items into a box. After 10 items have been passed i want the belt to stop. The bit I'm struggling with is the loop for item stopping.

int maxItem;
bool itemGone = false;

//Turning the conveyor belt on. 
if((GPIOA_PDIR & DETECTOR_MASK) != 0){
            for(maxItem = 0; maxItem 10; maxItem++){
                itemGone = true;
            }

How would the belt know that I 10 items have been passed?


Solution

  • I think I got what you tried to do. Correct me if I'm wrong, but you are checking the input only once in the code. The most correct would be something like this:

    int maxItem = 0;
    while ( maxItem < 10 )  // do the code while the number of items is less than 10 
    {
      if((GPIOA_PDIR & DETECTOR_MASK) != 0) //Checking the input to verify the item has entered the sensor
      {
        while ( (GPIOA_PDIR & DETECTOR_MASK) != 0); //wait for the sensor go back to normal (item has left the sensor)
    
        maxItem++;
    
      }
    }
    

    This way, no matter how many times it checks the input, it will only stop the conveyor belt when it sees 10 items have gone through. The while loop inside is necessary because you are checking the inputs thousands, even millions, of times in a short amount of time. NOTICE IT DOES NOTHING ELSE THAN CHECKING IF THE SENSOR CAME BACK TO ZERO. This way, you know the item has entered the sensor and left, allowing you to count properly (for any doubts, check on bounce and debounce logic for switching buttons). Also you have to check the logic for resetting the counter once the 10 items have passed, so you can start over again.