Hello,
I have an lcd ping pong game made.
However, my lecturer said that I should add something with asynchronous programming and interrupts. He suggested making a timer.
So I am considering adding a timer to my code so that the round would automatically end if it goes on for more than i.e. 60 seconds.
However, I have no idea how to do this.
Could anyone tell me how timers work and how should I go about adding one to my game?
If needed here is my code for reference:
#include <LiquidCrystal.h>
#include <math.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int px = 0, py = 0, ex = 15, ey = 0;
double bx = 8, by = 0.5, bVelX, bVelY;
int player = 0, bot = 0, gameCount = 0;
bool game;
byte ballMid[2][8] =
{
{
B00000,
B00000,
B00000,
B00000,
B00000,
B00000,
B01110,
B10001
},
{
B10001,
B01110,
B00000,
B00000,
B00000,
B00000,
B00000,
B00000
}
};
void setup()
{
lcd.begin(16, 2);
lcd.createChar(5, ballMid[0]);
lcd.createChar(6, ballMid[1]);
pinMode(6, INPUT);
randomSeed(analogRead(0));
bVelX = random(30, 60) / 100.0 * (random(0, 2) == 0 ? 1 : -1);
bVelY = random(10, 30) / 100.0 * (random(0, 2) == 0 ? 1 : -1);
Serial.begin(9600);
}
void loop()
{
game = update();
lcd.clear();
render();
if (!game || gameCount <= 0)
{
delay(gameCount <= 0 ? 3000: 1000);
gameCount++;
}
delay(60);
}
bool update()
{
py = digitalRead(6);
ey = (bx > 6 && random(0, 7) == 0 ? by : ey);
if (bx >= 15 || bx <= 0)
{
if ((bx <= 0 && (int) (by = round(by)) == py) || (bx > 15 && (int) by == ey))
{
bVelX = random(40, 60) / 100.0 * -sign(bVelX);
}
else
{
if (bx < 8)
bot++;
else
player++;
bx = random(6, 9);
by = random(0, 2);
bVelX = random(30, 60) / 100.0 * (random(0, 2) == 0 ? 1 : -1);
bVelY = random(10, 30) / 100.0 * -sign(bVelY);
return false;
}
}
if (by > 2 || by < 0)
bVelY = random(10, 30) / 100.0 * -sign(bVelY);
bx += bVelX;
if (bx > 2 && bx < 14)
by += bVelY;
else
by = round(clamp(by, 0, 1));
return true;
}
void render()
{
if (game && gameCount > 0)
{
lcd.setCursor(6, 0);
lcd.print(player);
lcd.print("/");
lcd.print(bot);
}
if (by < 0.8 && by > 0.2)
{
lcd.setCursor(bx, 0);
lcd.write(5);
lcd.setCursor(bx, 1);
lcd.write(6);
}
else
{
lcd.setCursor(bx, by);
lcd.print("o");
}
lcd.setCursor(px, py);
lcd.print("|");
lcd.setCursor(ex, ey);
lcd.print("|");
}
double clamp(double val, double min, double max)
{
return val > max ? max : val < min ? min : val;
}
double sign(double val) {
if (val < 0)
return -1;
else if (val==0)
return 0;
return 1;
}