<< return to Pixycam.com

Wasted CPU Power in hello_world Code

In the hello_world code, which comes in the Pixy library. The code wasted processioning power by uselessly wasting time. It may not actually be wasting processing power, I’m not quite sure.

Instead of incrementing ‘i’, ‘i’ should equal millis(), which returns the number of seconds since the Arduino was powered up. Then, adjust the number ‘i’ is compared to in the if statement to the number of seconds between each outputted update. This method provides better accuracy, and possibly wastes less processing power.

" if (blocks)
{
i++;

if (i%50==0)

" should be changed to "
if (blocks)
{
i=millis();

if (i%50==0)

".

Looking at the whole loop, it’s basically only a delay implemented based on how many detected blocks you are receiving from your Pixy. After every 50 blocks received, it will output the last block received to the serial port. If it did this for every block, the TX buffer in the Arduino’s UART would probably be overrun (I’m guessing).

So you don’t necessarily want to output some serial debugging information every 50 milliseconds. You just want to output some debugging info after you get a bunch of info (every 50 blocks). This is however just an example, and based on how you need to debug you may want to see more or less data. I find this scrolling collection of data in the Serial Terminal pretty confusing to read and quite useless by itself. Sure it’s telling you want Pixy sees, but it’s not realtime like the Pixymon Cooked video mode is, and it’s not really possible to read it all as it scrolls past. That said, it’s not meant to be useful necessarily I think. Just an example to show you how to access the data. And if you need more realtime data you should not put the serial output in there, or wait for every 50th block received.

Here’s the whole loop() for reference:

void loop()
{ 
  static int i = 0;
  int j;
  uint16_t blocks;
  char buf[32]; 
  
  blocks = pixy.getBlocks();
  
  if (blocks)
  {
    i++;
    
    if (i%50==0)
    {
      sprintf(buf, "Detected %d:\n", blocks);
      Serial.print(buf);
      for (j=0; j<blocks; j++)
      {
        sprintf(buf, "  block %d: ", j);
        Serial.print(buf); 
        pixy.blocks[j].print();
      }
    }
  }  
}

You’re exactly right, this was just meant to be an example to show how to use the Pixy Arduino library. We only output every 50th getBlocks since that equates to about 1 second. There are probably plenty of other ways to make the program wait, but this was just the first and easiest method we thought of when writing the code.

Scott

@BDub Yeah, I was thinking that if(blocks) was a while loop. That actually makes sense. I thought it was just being used to delay in a very unconvention way. Thanks