Arduino starts lagging

Hello,

For a school project, I am making the game Tetris on an Arduino Uno, using 2 LED 8x8 Matrix MAX721.

Because I save the fallen blocks, the game starts lagging after a while.

Is this because of the code or is this because of the Arduino?

Thanks in advance!

Yes.

An Arduino itself does not get slower over time. So must be your code :wink: Show it and don't forget the code tags. The simplest way

  1. In the IDE, use tools-> auto format to properly indent your code.
  2. In the IDE, use edit -> copy for forum to copy your code to the clipboard.
  3. Paste in a reply on the forum.

Your topic has been moved to a more suitable location on the forum. Installation and Troubleshooting is not for problems with (nor for advise on) your project.

For why?

a7

Have a counter summing up the fallen blocks as per size, 1, 2, 3 or more units in the blocks.
That's the display I've seen of Tetris playing various versions for 30+ years.

This is my code.
Sorry for the strange names, the names are from Dutch.

#include "LedControl.h"
LedControl lc = LedControl(7, 5, 6, 2);
int VRx = A0;
int VRy = A1;
int SW = 2;
int xPosition = 0;
int yPosition = 0;
int SW_state = 0;
int mapX = 0;
int mapY = 0;
char richting = 0;//direction
int volgendBlok = 0;//next block
boolean isBlok = false;// see if there is already a falling block
boolean controleGrond = false; //to see if the block is above the ground
int bHuidigX[] = {0, 0, 0, 0 }; //Array that keeps track of the x coordinates of the blocks that fall
int bHuidigY[] = {0, 0, 0, 0 }; //Array that keeps track of the y coordinates of the blocks that fall
int bewegingsnelheid = 0;//movement speed (moving left and right)
int snelheid = 0;//fall speed
int draai = 0;//rotational speed
boolean oBloks[8][16] = {{false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
  {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
  {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
  {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
  {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
  {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
  {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false},
  {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false}
};//  Array that stores the dropped blocks


boolean checkEind = false;//to detect if the game ends
bool lijndetected = false;//detect a full line
int volleLijnNummer = -1; // the line that is full


void setup()
{
  Serial.begin(9600);
  randomSeed(analogRead(A5));
  lc.shutdown(0, false);
  lc.shutdown(1, false);
  lc.setIntensity(0, 8);
  lc.setIntensity(1, 8);
  lc.clearDisplay(0);
  lc.clearDisplay(1);
  pinMode(VRx, INPUT);
  pinMode(VRy, INPUT);
  pinMode(SW, INPUT_PULLUP);

}
void loop()
{
  checkEinde();//looks if the game ends
  if (checkEind == false)
  {
    checkVolleRij();//checks for full rows
    verwijderBlok();// refreshes the screen (only the blocks that are falling)
    snelheid++;//adds speed (for delay)
    bewegingsnelheid++;//adds move speed (for delay)

    if (snelheid >= 10) // checks if delay is 10*10 = 100
    {
      if (isBlok == false)
      {
        isBlok = true;
        randomBlok();   //spawns new block
      }
      zakBlok();// let the block drop one by one
      snelheid = 0;// delay resets
    }
    if (bewegingsnelheid >= 9 && controleGrond == false)
    {
      besturen();//movement of the block
      bewegingsnelheid = 0;
    }

    toonBlok();//shows the falling  block
    toonoBlok();//shows the blocks that are saved
  }
  else if (checkEind == true)
  {
  }
  delay(10);
}
void checkVolleRij()//checks for full rows
{

  for (int i = 0; i < 16; i++)
  {
    if (oBloks[0][i] == 1 && oBloks[1][i] == 1 && oBloks[2][i] == 1 && oBloks[3][i] == 1 && oBloks[4][i] == 1 && oBloks[5][i] == 1 && oBloks[6][i] == 1 && oBloks[7][i] == 1)
    {
      volleLijnNummer = i;
    }
  }

  if (volleLijnNummer > -1)
  {
    lijndetected = true;
  }
  else
  {
    lijndetected = false;
  }
  if (lijndetected == true)
  {
    for (int i = 0; i < 8; i++)
    {
      oBloks[i][volleLijnNummer] = 0;
    }
    for (int i = 0; i < 16; i++)
    {
      for (int j = 0; j < 8; j++)
      {
        if (i > volleLijnNummer)
        {
          if (oBloks[j][i] == true)
          {
            oBloks[j][i] = false;
            oBloks[j][i - 1] = true;
          }
        }
      }
    }
    lijndetected = false;
    volleLijnNummer = -1;
    lc.clearDisplay(0);
    lc.clearDisplay(1);
  }
}

void checkEinde()//checks for end
{
  for (int i = 0; i < 8; i++)
  {
    if (oBloks[i][15] == true)
    {
      checkEind =  true;
    }
  }
}
//methode
void toonoBlok()// turns on the blocks that are saved
{
  for (int i = 0; i < 8; i++)
  {
    for (int y = 0 ; y < 16; y++)
    {
      if (oBloks[i][y] == 1)
      {
        ledje(i, y, true);
      }
    }
  }
}

void oBlok()//saves the fallen blocks
{
  for (int i = 0; i < 4; i++)
  {
    oBloks[bHuidigX[i]][bHuidigY[i]] = 1;
  }
}
boolean checkOnder()//checks if the block still can go down
{
  for (int i = 0; i < 4; i++)
  {
    int checkX = bHuidigX[i];
    int checkY = bHuidigY[i] - 1;
    if (oBloks[checkX][checkY] == 1 || bHuidigY[i] <= 0)
    {
      return true;
    }
  }
  return false;
}
void zakBlok()//lower the block
{
  if (checkOnder() == true)
  {
    oBlok();
    isBlok = false;
    controleGrond = false;
    draai = 0;
  }
  else
  {
    for (int i = 0;  i < 4; i++)
    {
      bHuidigY[i]--  ;
    }
  }
}

char positie()//position of the joystick
{
  if ( mapX > -100 && mapX < 100 && mapY > -100 && mapY < 100)
  {
    richting = 0;//deadzone
    return richting;
  }
  else if (mapX > 0 && mapY > 0)
  {
    //Serial.println("Kwadrant 1");
    if (abs(mapY) < abs(mapX))
    {
      richting = 1;//up
      return richting;
    }
    else if ( abs(mapY) > abs(mapX))
    {
      richting = 3;//right
      return richting;
    }
  }
  else if (mapX < 0 && mapY > 0)
  {
    if (mapY >= mapX)
    {
      richting = 2;//down
      return richting;
    }
    else if (mapY < mapX)
    {
      richting = 4;//left
      return richting;
    }
  }
  else if (mapX < 0 && mapY < 0)
  {
    if (mapY >= mapX)
    {
      richting = 2;
      return richting;
    }
  }
  else if (mapX > 0 && mapY < 0)
  {
    //Serial.println("Kwadrant 4");
    if (abs(mapY) < abs(mapX))
    {
      richting = 1;
      return richting;
    }
    else if (mapY < mapX)
    {
      richting = 4;
      return richting;
    }
  }
}
void besturen()//to move the blocks left and right + rotate the block
{
  boolean zijkantL = false;
  boolean zijkantR = false;
  xPosition = analogRead(VRx);
  yPosition = analogRead(VRy);
  SW_state = digitalRead(SW);
  mapX = map(xPosition, 0, 1023, -512, 512);
  mapY = map(yPosition, 0, 1023, -512, 512);
  if (zijkantR == false || zijkantL == false)
  {
    for (int i = 0; i < 4; i++)
    {
      if (bHuidigX[i] < 1)
      {
        zijkantR = true;
      }
      if (bHuidigX[i] > 6)
      {
        zijkantL = true;
      }
    }
  }
  if (positie() == 3)
  {
    for (int i = 0; i < 4; i++)
    {
      if (zijkantR == false)
      {
        bHuidigX[i]-- ;
      }
    }
  }
  if (positie() == 4)
  {
    for (int i = 0; i < 4; i++)
    {
      if (zijkantL == false)
      {
        //Serial.println(bHuidigX[i]);
        bHuidigX[i]++ ;

      }
    }
  }
  if (positie() == 1) //draaien
  {
    if (volgendBlok != 0)
    {
      if (volgendBlok == 1) //I
      {
        if (draai == 0)
        {
          draai = 1;
          bHuidigX[0] += 2;
          bHuidigY[0] -= 3;
          bHuidigX[1]++;
          bHuidigY[1] -= 2;
          bHuidigY[2]--;
          bHuidigX[3]--;
        }
        else if (draai == 1)
        {
          draai = 0;
          bHuidigX[0] -= 2;
          bHuidigY[0] += 3;
          bHuidigX[1]--;
          bHuidigY[1] += 2;
          bHuidigY[2]++;
          bHuidigX[3]++;
        }
      }
      else if (volgendBlok == 2) //L
      {
        if (draai == 0)
        {
          draai = 1;
          bHuidigX[0]--;
          bHuidigY[0]--;
          bHuidigY[2]--;
          bHuidigX[2]++;
          bHuidigX[3] += 2;
          bHuidigY[3] -= 2;
        }
        else if (draai == 1)
        {
          draai = 2;
          bHuidigX[0]--;
          bHuidigY[0]--;
          bHuidigX[1] -= 2;
          bHuidigY[2]++;
          bHuidigX[2]--;
          bHuidigX[3];
          bHuidigY[3] += 2;
        }
        else if (draai == 2)
        {
          draai = 3;
          bHuidigX[0]++;
          bHuidigY[1]--;
          bHuidigX[2]--;
          bHuidigX[3] -= 2;
          bHuidigY[3]++;
        }
        else if (draai == 3)
        {
          draai = 0;
          bHuidigX[0]++;
          bHuidigY[0] += 2;
          bHuidigY[1]++;
          bHuidigX[1] += 2;
          bHuidigX[2]++;
          bHuidigY[3]--;

        }
      }
      else if (volgendBlok == 3)
      {
        if (draai == 0)
        {
          draai = 1;
          bHuidigX[0]--;
          bHuidigY[0] += 2;
          bHuidigY[1]++;
          bHuidigX[2]++;
          bHuidigY[3]--;
        }
        else if (draai == 1)
        {
          draai = 2;
          bHuidigX[0] -= 2;
          bHuidigY[0] -= 2;
          bHuidigX[1]--;
          bHuidigY[1]--;
          bHuidigX[3]++;
          bHuidigY[3]--;
        }
        else if (draai == 2)
        {
          draai = 3;
          bHuidigX[0]++;
          bHuidigY[0]--;
          bHuidigX[2]--;
          bHuidigY[2]++;
          bHuidigY[3] += 2;
        }
        else if (draai == 3)
        {
          draai = 0;
          bHuidigX[0] += 2;
          bHuidigX[1]++;
          bHuidigY[1]--;
          bHuidigY[2] -= 2;
          bHuidigX[3]--;
          bHuidigY[3]--;
        }
      }
      else if (volgendBlok == 4)
      {
        if (draai == 0)
        {
          draai = 1;
          bHuidigX[0] -= 2;
          bHuidigY[0]++;
          bHuidigX[1]--;
          bHuidigY[2]++;
          bHuidigX[3]++;
        }
        else if (draai == 1)
        {
          draai = 0;
          bHuidigX[0] += 2;
          bHuidigY[0]--;
          bHuidigX[1]++;
          bHuidigY[2]--;
          bHuidigX[3]--;

        }
      }
      else if (volgendBlok == 5)
      {
        if (draai == 0)
        {
          draai = 1;
          bHuidigX[0] -= 2;
          bHuidigY[1] += 2;
        }
        else if (draai == 1)
        {
          draai = 0;
          bHuidigX[0] += 2;
          bHuidigY[1] -= 2;
        }
      }
      else if (volgendBlok == 6)
      {
        if (draai == 0)
        {
          draai = 1;
          bHuidigX[0]--;
          bHuidigY[0]--;
        }
        else if (draai == 1)
        {
          draai = 2;
          bHuidigX[0]++;
          bHuidigY[0]++;
          bHuidigY[2] -= 2;
        }
        else if (draai == 2)
        {
          draai = 3;
          bHuidigY[2] += 2;
          bHuidigY[3]--;
          bHuidigX[3]++;
        }
        else if (draai == 3)
        {
          draai = 0;
          bHuidigX[3]--;
          bHuidigY[3]++;
        }
      }
    }
  }
}

void ledje(int x , int y, boolean aan)//alternative of lc.setLed, so it was easier to work with 2 screens
{
  if (aan == true)
  {
    if ( y >= 0 && y <= 7)
    {
      lc.setLed(0, y, x, true);
    }
    if (  y >= 8 && y <= 15  && aan == true)
    {
      y = y - 8;
      lc.setLed(1, y, x, true);
    }
  }
  else if ( y >= 0 && y <= 7)
  {
    lc.setLed(0, y, x, false);
  }
  else
  {
    y = y - 8;
    lc.setLed(1, y, x, false);
  }
}

void randomBlok()// generates a random block
{

  volgendBlok = random(-1, 7);

  if (volgendBlok == 0) // V
  {
    bHuidigX[0] = 4;
    bHuidigX[1] = 3;
    bHuidigX[2] = 4;
    bHuidigX[3] = 3;
    bHuidigY[0] = 15;
    bHuidigY[1] = 15;
    bHuidigY[2] = 14;
    bHuidigY[3] = 14;
  }
  if (volgendBlok == 1) // I
  {
    bHuidigX[0] = 2;
    bHuidigX[1] = 3;
    bHuidigX[2] = 4;
    bHuidigX[3] = 5;
    bHuidigY[0] = 15;
    bHuidigY[1] = 15;
    bHuidigY[2] = 15;
    bHuidigY[3] = 15;
  }
  if (volgendBlok == 2) // L
  {
    bHuidigX[0] = 5;
    bHuidigX[1] = 5;
    bHuidigX[2] = 4;
    bHuidigX[3] = 3;
    bHuidigY[0] = 15;
    bHuidigY[1] = 14;
    bHuidigY[2] = 14;
    bHuidigY[3] = 14;
  }
  if (volgendBlok == 3) // J
  {
    bHuidigX[0] = 5;
    bHuidigX[1] = 4;
    bHuidigX[2] = 3;
    bHuidigX[3] = 3;
    bHuidigY[0] = 14;
    bHuidigY[1] = 14;
    bHuidigY[2] = 14;
    bHuidigY[3] = 15;
  }
  if (volgendBlok == 4) // Z
  {
    bHuidigX[0] = 5;
    bHuidigX[1] = 4;
    bHuidigX[2] = 4;
    bHuidigX[3] = 3;
    bHuidigY[0] = 15;
    bHuidigY[1] = 15;
    bHuidigY[2] = 14;
    bHuidigY[3] = 14;
  }
  if (volgendBlok == 5) // S
  {
    bHuidigX[0] = 5;
    bHuidigX[1] = 4;
    bHuidigX[2] = 4;
    bHuidigX[3] = 3;
    bHuidigY[0] = 14;
    bHuidigY[1] = 14;
    bHuidigY[2] = 15;
    bHuidigY[3] = 15;
  }
  if (volgendBlok == 6) //T
  {
    bHuidigX[0] = 5;
    bHuidigX[1] = 4;
    bHuidigX[2] = 4;
    bHuidigX[3] = 3;
    bHuidigY[0] = 14;
    bHuidigY[1] = 14;
    bHuidigY[2] = 15;
    bHuidigY[3] = 14;
  }
}

void toonBlok()//shows the block that is falling
{
  for ( int i = 0 ; i < 4; i++)
  {
    ledje(bHuidigX[i], bHuidigY[i], true);
  }
}

void verwijderBlok()//turn off the leds of the falling block
{
  for ( int i = 0 ; i < 4; i++)
  {
    ledje(bHuidigX[i], bHuidigY[i], false);
  }
}

I wonder about this

at the end of your loop().

Is it necessary to limit the loop speed here, in this manner?

I understand that there are timed elements to a game played by humans, but you can get a 100 Hz "frame rate" and still leave the processor available to do the (increasing amount of) work which is tracking and updating the falling blocks.

What happens if you just remove that delay? The game may be unplayable, but I think you will see it operating very rapidly.

a7

Hi,

First of all, thank you for your answer!

I have removed the delay as you said. At first, the blocks will fall faster, but now it is more noticeable that the game is going slower over time.

Maxime0602

Ok, that’s what I would have expected.

I’m away from the big rig, but will try to see if your algorithms are not the problem…

It seems like Tetris calculations shouldn’t take that long - perhaps it is the need to display an increased number of blocks that slows you down.

It might be easy for you temporarily modify your sketch to run the algorithms for position and such like, but omit the actual display of the blocks. This would let you see if that indeed is you bottleneck.

a7

Perhaps a stupid question, if I leave out the display of the blocks.

How will I then be able to see that the game is slowing down?

No, not stupid.

You could do put some Serial.print statements in there. Use a high baud rate.

You could blink an LED and watch it, or monitor the digital output (or several) with an oscilloscope or logic probe.

You don’t have a logic probe? You can get a cheap but entirely serviceable unit for around $10, very easy to use.

  8 channel 24 mhz logic probe

added: you could also just see how fast you can do nothing but drawing the blocks. Draw more and more and see if you are slowing down in the same manner.

If you can't do the block drawing fast enough, it would mean tht's where to focus.

a7

So, I looked a bit at the time when I used Serial.print.
I looked at how long it takes to count from 1-10.

If I leave out the display of the blocks, you can clearly see that it averages around 100 ms.

But when I put the blocks back in, there was a big difference towards the end! It took at the end no less than 750-700 ms to count from 1-10.

So there is a problem in the code for displaying the blocks.

Maxime0602

So I've looked in my code, but I can't find the reason why my code slows down.

Do you have any ideas?

I thought more blocks meant slower.

Can you do an experiment where all you do is draw blocks, no code for Tetris or anything else.

Just to see if it is at a low level. If you need to draw N blocks in a certain time but the hardware can’t do that, you’ll need to rethink the hardware you use.

I don’t think it’s the problem, but I would check that first before evaluating your Tetris code with an eye to improving the algorithms you use for making the Tetris stuff happen.

a7

Hi,

so I left out the appearance of the saved blocks. Then the speed remains the same throughout the game.

Then as soon as I put in the method for displaying the saved blocks again, the game starts slowing down again.

So the reason lies with toonoBlok(). The code that goes with it is:

void toonoBlok()// turns on the blocks that are saved
{
  for (int i = 0; i < 8; i++)
  {
    for (int y = 0 ; y < 16; y++)
    {
      if (oBloks[i][y] == 1)
      {
        ledje(i, y, true);
      }
    }
  }
}

Is it because of the 2 different for loops that are in each other that the game starts to slow down?

No I don't think so. That's a perfectly good nested loop, you always look at 128 cases, so it is the increased number of calls to ledge that seem to take increased amount of time.

I placed the code into a simulation at wokwi.com. I hacked your code to just see how long some things take.

Your loops take essentially no time.

Calling lc.setLed() takes about 0.5 ms. If all the blocks are on, that's 128 * 0.5 or 64 ms, or a 16 Hz frame rate if you were doing nothing else.

16 Hz Tetris would def feel laggy, and anything slower only more so. Laggy. I assume your Tetris calculations are straight forward and fairly simple, it is possible you have an inefficient algorithm, but the a limit or "bottleneck" will be that 0.5 ms per block every frame.

Take a look at the simulation. I moved the functions I was looking at up for convenience and wrote a few lines to just see how long things take.

You can use the same pattern to test various things. In particular, you might try to find a faster way to lc.setLed or it may actually be faster to program something so you don't have to call setLed if you don't need to... like using the array track of blocks to omit calls to positions that are correctly set already.

https://wokwi.com/arduino/projects/321962020145463891

HTH

a7

OK so I wondered why setLed is so slow, or seems slow.

Poking around I found

https://wayoda.github.io/LedControl/pages/software

which makes interesting reading, at least for those of us with no life.

It points out that it is slow to talk to one LED at a time… there are functions to do an entire row at once that the page says are faster.

Your data structure that informs the LED setting ps on or off might be close to a form in which you could do whole rows (or was it columns?) at a time.

It might take less time to form the data ahead of calls to setRow instead of one LED at a time.

Or you might think again about your local representation of the grid and make it be formatted with an eye to the idea that you want to call setRow. Like if you used individual bits in bytes.

Yes: more fussing with the bits. Maybe: faster rendering because you data is ready to go.

Did I mention looking into seeing if you can know when you don’t need to call anything to set an LED (or group) because they are already all correct? That checking and avoiding the call may be faster than just making the call…

Time for experimentation with measurements. I would design some experiments that can stand alone, that is with no Tetris stuff, just test of other data structures to hold the grid and seeing how fast it can be thrown.

Or you could rename your game, remove or slow down the time element and make it a calm strategic slow process. :wink:

a7

OK bad day for the beach anyway, so I did an experiment with two derivatives of toonoBolk,

where in one version I employed setRow to do 8 LEDs at a time and saw a substantial savings of time.

It isn't directly compatible with your toonoBlob function because I did not bother with the ledge function you use to handle two displays. Haven't looked into that.

So if you use this idea, you'll have to figure out how to make it fit into your scheme.

It may turn out better to have less convenience at the time of writing the code for more speed when it is running. This is not untypical. The fastest programs take the longest to write! And can involve code that appears redundant...

I left everything in the wokwi, if you can read it you may see that I tried a few things, also set up two arrays pre-filled with values to tax the functions. I just commented things in and out.

TBH I have no idea if this is the proper tree to be barking up. But I do think that there is a benefit to figuring out how to use setRow.

a7

Hi Alto777,

I did what you suggested.
It works perfectly now, the game doesn't slow down anymore.
I am extremely grateful for your help!

Maxime0602

Yay!

Thank you for reporting.

And thank you for rekindling my interest in Tetris. :wink:

a7