#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// OLED display dimensions
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// I2C address for the OLED display
#define OLED_I2C_ADDRESS 0x3C
// Initialize the OLED display object
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire);
int xPos = 0; // X position of the rectangle
int speed = 2; // Speed of the rectangle
void setup() {
// Start serial communication (optional for debugging)
Serial.begin(9600);
// Initialize the display
if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_I2C_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Halt if initialization fails
}
// Clear the display
display.clearDisplay();
}
void loop() {
display.clearDisplay(); // Clear the screen
// Draw the moving rectangle
display.fillRect(xPos, 20, 30, 20, SSD1306_WHITE); // Draw rectangle at new x position
// Update the display
display.display();
// Update position for animation effect
xPos += speed; // Increase position by speed
// Reverse direction if rectangle hits the edges of the screen
if (xPos > SCREEN_WIDTH - 30 || xPos < 0) {
speed = -speed; // Reverse the direction
}
delay(20); // Control animation speed
}