Wiring:
Vcc--->5V
GND--->GND
SDA----->Arduino A4
SCL----->Arduino A5
Potentiometer 1: GND, A0, 5V
Potentiometer 2: GND, A1, 5V
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
int ballX = 7, ballY = 0;
int ballDirX = 1, ballDirY = 1;
int paddle1Pos, paddle2Pos;
void setup() {
lcd.begin(); // Use lcd.init() for newer I2C libraries
lcd.backlight();
pinMode(A0, INPUT);
pinMode(A1, INPUT);
pinMode(7, OUTPUT);
pinMode(8,OUTPUT);
digitalWrite(7, HIGH);
digitalWrite(8,HIGH);
}
void loop() {
// 1. Read Potentiometers for both players
// Map 0-1023 to 0-1 (the two rows of the LCD)
paddle1Pos = map(analogRead(A0), 0, 1023, 0, 1);
paddle2Pos = map(analogRead(A1), 0, 1023, 0, 1);
// 2. Move Ball
ballX += ballDirX;
ballY += ballDirY;
// 3. Wall Collisions (Top and Bottom)
if (ballY <= 0 || ballY >= 1) {
ballDirY = -ballDirY;
}
// 4. Paddle Collisions (Left and Right)
// Player 1 (Left side - Column 0)
if (ballX == 0) {
if (ballY == paddle1Pos) {
ballDirX = -ballDirX; // Bounce!
} else {
resetGame(); // Missed!
}
}
// Player 2 (Right side - Column 15)
if (ballX == 15) {
if (ballY == paddle2Pos) {
ballDirX = -ballDirX; // Bounce!
} else {
resetGame(); // Missed!
}
}
// 5. Render
lcd.clear();
// Draw Paddle 1
lcd.setCursor(0, paddle1Pos);
lcd.print("|");
// Draw Paddle 2
lcd.setCursor(15, paddle2Pos);
lcd.print("|");
// Draw Ball
lcd.setCursor(ballX, ballY);
lcd.print("o");
delay(200); // Game speed (lower is faster)
}
void resetGame() {
ballX = 7;
ballY = 0;
ballDirX = -ballDirX; // Send it to the person who just scored
lcd.clear();
lcd.setCursor(5, 0);
lcd.print("OUT!");
delay(1000);
}