Arduino UNO R4 LED Matrix

Hướng dẫn này sẽ hướng dẫn bạn cách sử dụng Arduino UNO R4 với các module màn hình LED matrix bên ngoài. Cụ thể, chúng ta sẽ học:

Sau đó, bạn có thể dễ dàng sửa đổi code cho các LED matrix khác như LED matrix 16x8 hoặc 64x8.

Arduino UNO R4 LED matrix

Nếu bạn muốn học về cách sử dụng Arduino R4 với LED Matrix tích hợp sẵn, vui lòng tham khảo Arduino UNO R4 - Ma Trận LED Tích Hợp

Phần Cứng Cần Thiết

1×Arduino UNO R4 WiFi hoặc Arduino UNO R4 Minima
1×(Tùy chọn) DIYables STEM V4 IoT, tương thích với Arduino Uno R4 WiFi Amazon
1×Arduino UNO R4 Minima (Thay thế) Amazon
1×Cáp USB Type-C Amazon
1×FC-16 LED Matrix 32x8 Amazon
1×FC-16 LED Matrix 8x8 Amazon
1×Dây Jumper Amazon
1×DC Power Jack Amazon
1×Adapter Nguồn 5V cho Arduino UNO R4 Amazon
1×(Khuyến nghị) Screw Terminal Block Shield for Arduino UNO R4 Amazon
1×(Khuyến nghị) Sensors/Servo Expansion Shield for Arduino UNO R4 Amazon
1×(Khuyến nghị) Breadboard Shield for Arduino UNO R4 Amazon
1×(Khuyến nghị) Enclosure for Arduino UNO R4 Amazon
1×(Khuyến nghị) Power Splitter for Arduino UNO R4 Amazon
1×(Khuyến nghị) Prototyping Base Plate & Breadboard Kit for Arduino UNO Amazon

Or you can buy the following kits:

1×DIYables STEM V4 IoT Starter Kit (Arduino included) Amazon
1×DIYables STEM V4B IoT Starter Kit (Arduino included) Amazon
1×DIYables Sensor Kit (18 sensors/displays) Amazon
Tiết lộ: Một số liên kết trong bài viết này là liên kết tiếp thị Amazon và có thể nhận hoa hồng theo chính sách của chương trình.
Arduino Uno R4 WiFi Compatible Boards

Về LED Matrix

LED matrix màn hình

Có nhiều loại LED Matrix khác nhau. LED matrix dựa trên MAX7219 được sử dụng phổ biến với Arduino UNO R4. LED matrix này bao gồm một số đặc điểm:

  • Thành phần cơ bản của LED matrix được gọi là block (khối).
  • Mỗi block chứa lưới LED 8x8, tổng cộng 64 LED, và được điều khiển bởi chip MAX7219.
  • Có hai loại block chính: module thông thường và module FC-16.
  • LED matrix có thể chỉ có một block hoặc được mở rộng bằng cách kết nối nhiều block lại với nhau như một chuỗi.
  • Bạn có thể mua LED matrix đã có nhiều block được kết nối sẵn, chẳng hạn như cấu hình 4-block hoặc 8-block.
  • Hoặc bạn có thể mua từng block riêng lẻ và tự kết nối chúng để tạo LED matrix với kích thước bạn cần.
  • Trong chương trình Arduino UNO R4, bạn phải chỉ định kích thước của LED matrix mà bạn đang sử dụng.

Sơ Đồ Chân

LED matrix sơ đồ chân

LED Matrix được tạo thành từ một hoặc nhiều block. Mỗi block có hai nhóm chân:

  • Nhóm Chân Đầu Vào:
    • VCC: Kết nối với 5V.
    • GND: Kết nối với GND.
    • DIN: Đây là chân Data. Kết nối với chân SPI MOSI trên Arduino UNO R4.
    • CS: Chip Select. Kết nối với bất kỳ chân digital nào trên Arduino UNO R4.
    • CLK: Chân Clock. Kết nối với chân SPI CLK trên Arduino UNO R4.
  • Nhóm Chân Đầu Ra:
    • VCC: Kết nối với VCC trên module tiếp theo.
    • GND: Kết nối với GND trên module tiếp theo.
    • DOUT: Data Out. Kết nối với chân DIN trên module tiếp theo.
    • CS: Kết nối với CS trên module tiếp theo.
    • CLK: Kết nối với CLK trên module tiếp theo.

Sơ Đồ Kết Nối

Nếu LED matrix chỉ gồm một block:

  • Kết nối nhóm chân đầu vào với Arduino UNO R4.
  • Để nhóm chân đầu ra không kết nối.
Arduino UNO R4 8x8 LED matrix fc-16 sơ đồ đấu dây

This image is created using Fritzing. Click to enlarge image

Arduino UNO R4 8x8 LED matrix generic sơ đồ đấu dây

This image is created using Fritzing. Click to enlarge image

Nếu LED matrix được lắp ráp sẵn thành nhiều block:

  • Kết nối nhóm chân đầu vào với Arduino UNO R4.
  • Để nhóm chân đầu ra không kết nối.
Arduino UNO R4 LED matrix màn hình sơ đồ đấu dây

This image is created using Fritzing. Click to enlarge image

Dây của module và dây to thường không cắm chặt vào header cái. Bạn có thể gắn Proto Screw Terminal Block Shield hoặc Screw Shield V2 lên Arduino UNO R4 và nối dây vào các cầu đấu vít của nó. Đây là cùng mạch điện, nối qua Screw Shield V2:

Arduino UNO R4 LED matrix màn hình sơ đồ đấu dây (screw shield v2)

This image is created using Fritzing. Click to enlarge image

Nếu bạn lắp ráp LED matrix từ nhiều phần:

  • Kết nối nhóm chân đầu vào của block đầu tiên với Arduino UNO R4.
  • Kết nối nhóm chân đầu ra của mỗi block với nhóm chân đầu vào của block tiếp theo.
  • Để nhóm chân đầu ra của block cuối cùng không kết nối.
Arduino UNO R4 32x8 LED matrix wiring fc-16 diagram

This image is created using Fritzing. Click to enlarge image

Arduino UNO R4 32x8 LED matrix wiring generic diagram

This image is created using Fritzing. Click to enlarge image

Màn hình sử dụng rất nhiều điện, lên đến 1 ampere ở độ sáng tối đa.

  • Tránh sử dụng chân 5V trên Arduino UNO R4 để cấp điện.
  • Thay vào đó, hãy kết nối nguồn 5V bên ngoài. Arduino UNO R4 và LED matrix đều có thể được cấp điện bởi cùng một adapter 5V.

Arduino UNO R4 kết nối với LED matrix sử dụng chân SPI.

  • Sử dụng chân 13 (SCK) và 11 (MOSI) trên Arduino UNO R4. Nếu sử dụng bo mạch Arduino UNO R4 khác, hãy xem hướng dẫn chính thức cho các chân SPI tương ứng.
  • Bạn có thể sử dụng bất kỳ chân nào khác cho Pin 3 (CS).

Cách Lập Trình Cho LED Matrix

Điều khiển LED matrix có thể phức tạp. May mắn thay, có các thư viện giúp đơn giản hóa nhiệm vụ này. Dưới đây là các bước để lập trình Arduino UNO R4 điều khiển LED matrix.

  • Include thư viện:
#include <MD_Parola.h> #include <MD_MAX72xx.h>
  • Chọn loại phần cứng bạn đang sử dụng: GENERIC_HW hoặc FC16_HW.
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
  • Xác định số lượng block LED được sử dụng. Ví dụ, LED matrix 4-in-1 chứa 4 block.
#define MAX_DEVICES 4
  • Đặt chân kết nối với chân CS trên LED matrix. Ví dụ, sử dụng chân D9.
#define CS_PIN 9
  • Tạo một phiên bản mới của class MD_Parola cho màn hình LED matrix.
MD_Parola ledMatrix = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
  • Thiết lập code trong hàm setup().
void setup() { ledMatrix.begin(); // Khởi tạo LED matrix ledMatrix.setIntensity(0); // Đặt độ sáng màn hình (phạm vi 0-15) ledMatrix.displayClear(); // Xóa màn hình hiển thị }
  • Hiển thị văn bản, số, và hiệu ứng động: xem phần tiếp theo.

Arduino UNO R4 - Code LED Matrix

Code được cung cấp dành cho màn hình LED matrix FC-16 32x8 với bốn block. Tuy nhiên, nó có thể được sửa đổi cho các kích thước khác như 8x8, 16x8, 64x8, v.v.

/* * Mã Arduino UNO R4 này được phát triển bởi newbiely.vn * Mã Arduino UNO R4 này được cung cấp để sử dụng công khai, không có ràng buộc. * Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: * https://newbiely.vn/tutorials/arduino-uno-r4/arduino-uno-r4-led-matrix */ #include <MD_Parola.h> #include <MD_MAX72xx.h> #define HARDWARE_TYPE MD_MAX72XX::FC16_HW #define MAX_DEVICES 4 // 4 blocks #define CS_PIN 9 // The Arduino UNO R4 pin connected to the CS pin of LED matrix // create an instance of the MD_Parola class MD_Parola ledMatrix = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES); void setup() { ledMatrix.begin(); // initialize the object ledMatrix.setIntensity(15); // set the brightness of the LED matrix display (from 0 to 15) ledMatrix.displayClear(); // clear LED matrix display } void loop() { ledMatrix.setTextAlignment(PA_LEFT); ledMatrix.print("Left"); // display text delay(2000); ledMatrix.setTextAlignment(PA_CENTER); ledMatrix.print("Center"); // display text delay(2000); ledMatrix.setTextAlignment(PA_RIGHT); ledMatrix.print("Right"); // display text delay(2000); ledMatrix.setTextAlignment(PA_CENTER); ledMatrix.setInvert(true); ledMatrix.print("Invert"); // display text inverted delay(2000); ledMatrix.setInvert(false); ledMatrix.print(1234); // display number delay(2000); }

Các Bước Nhanh

Thực hiện theo các hướng dẫn này từng bước:

  • Nếu đây là lần đầu tiên bạn sử dụng Arduino Uno R4 WiFi/Minima, hãy tham khảo hướng dẫn về Arduino UNO R4 - Cài Đặt Phần Mềm.
  • Kết nối bo mạch Arduino Uno R4 với LED matrix theo sơ đồ được cung cấp.
  • Kết nối bo mạch Arduino Uno R4 với máy tính của bạn bằng cáp USB.
  • Khởi chạy Arduino IDE trên máy tính của bạn.
  • Chọn bo mạch Arduino Uno R4 phù hợp (ví dụ: Arduino Uno R4 WiFi) và cổng COM.
  • Trong Arduino IDE, nhấp vào biểu tượng Libraries ở thanh bên trái.
  • Tìm kiếm "MD_Parola" và định vị thư viện MD_Parola.
  • Nhấp nút Install.
Arduino UNO R4 md_parola thư viện
  • Bạn cần cài đặt thư viện MD_MAX72XX. Vui lòng nhấp nút Install All.
Arduino UNO R4 md_max72xx thư viện
  • Sao chép code ở trên và mở nó bằng Arduino IDE.
  • Nhấp nút Upload trong Arduino IDE để tải code lên Arduino UNO R4.
  • Quan sát màn hình hiển thị trên LED matrix.

Arduino UNO R4 Code LED Matrix – Text Cuộn

Khi bạn cần hiển thị thông điệp dài trên màn hình LED matrix và nó quá dài để vừa với màn hình, bạn có thể sử dụng hiệu ứng text cuộn.

Code Arduino UNO R4 này minh họa cách làm cho thông điệp cuộn qua màn hình LED matrix.

/* * Mã Arduino UNO R4 này được phát triển bởi newbiely.vn * Mã Arduino UNO R4 này được cung cấp để sử dụng công khai, không có ràng buộc. * Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: * https://newbiely.vn/tutorials/arduino-uno-r4/arduino-uno-r4-led-matrix */ #include <MD_Parola.h> #include <MD_MAX72xx.h> #define HARDWARE_TYPE MD_MAX72XX::FC16_HW #define MAX_DEVICES 4 // 4 blocks #define CS_PIN 9 // The Arduino UNO R4 pin connected to the CS pin of LED matrix // create an instance of the MD_Parola class MD_Parola ledMatrix = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES); void setup() { ledMatrix.begin(); // initialize the object ledMatrix.setIntensity(15); // set the brightness of the LED matrix display (from 0 to 15) ledMatrix.displayClear(); // clear led matrix display ledMatrix.displayScroll("Hello, DIYables", PA_CENTER, PA_SCROLL_LEFT, 100); } void loop() { if (ledMatrix.displayAnimate()) { ledMatrix.displayReset(); } }

Để xem thêm các hiệu ứng text, hãy truy cập Tài Liệu Tham Khảo Thư Viện MD_Parola.

Video Tutorial

Việc sản xuất video tốn rất nhiều thời gian. Nếu video hướng dẫn hữu ích cho việc học của bạn, hãy đăng ký kênh YouTube để ủng hộ. Nếu nhu cầu đủ cao, chúng tôi sẽ cố gắng làm thêm nhiều video.

Video demo bên dưới sử dụng đoạn mã bên dưới:

/* * Mã Arduino UNO R4 này được phát triển bởi newbiely.vn * Mã Arduino UNO R4 này được cung cấp để sử dụng công khai, không có ràng buộc. * Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: * https://newbiely.vn/tutorials/arduino-uno-r4/arduino-uno-r4-led-matrix */ #include <MD_MAX72xx.h> #include <SPI.h> // ============================================================ // MAX7219 // ============================================================ #define HARDWARE_TYPE MD_MAX72XX::FC16_HW #define MAX_DEVICES 4 #define CS_PIN 9 MD_MAX72XX mx = MD_MAX72XX(HARDWARE_TYPE, CS_PIN, MAX_DEVICES); // ============================================================ // BUTTONS // ============================================================ #define BTN_LEFT 2 #define BTN_RIGHT 3 #define BTN_ROTATE 4 #define BUZZER_PIN 6 // ============================================================ // GAME BOARD // ============================================================ #define BOARD_W 8 #define BOARD_H 32 bool board[BOARD_H][BOARD_W]; // ============================================================ // TIMING // ============================================================ unsigned long lastFallTime = 0; const unsigned long NORMAL_FALL = 700; const unsigned long SOFT_DROP_FALL = 80; #define LONG_PRESS_TIME 400 // ============================================================ // SCORE // ============================================================ unsigned long score = 0; unsigned int lines = 0; unsigned int level = 1; unsigned long highScore = 0; // ============================================================ // GAME STATE // ============================================================ bool gameOver = false; bool gameStarted = false; // ============================================================ // TETROMINO DEFINITIONS // ============================================================ struct Point { int x; int y; }; struct Tetromino { Point block[4]; uint8_t color; }; Tetromino pieces[7] = { // I { {{0,0}, {1,0}, {2,0}, {3,0}}, 0 }, // O { {{0,0}, {1,0}, {0,1}, {1,1}}, 1 }, // T { {{1,0}, {0,1}, {1,1}, {2,1}}, 2 }, // L { {{0,0}, {0,1}, {0,2}, {1,2}}, 3 }, // J { {{1,0}, {1,1}, {1,2}, {0,2}}, 4 }, // S { {{1,0}, {2,0}, {0,1}, {1,1}}, 5 }, // Z { {{0,0}, {1,0}, {1,1}, {2,1}}, 6 } }; // ============================================================ // CURRENT PIECE // ============================================================ int currentPiece; int currentX; int currentY; int rotationState = 0; // ============================================================ // BUTTON STATE // ============================================================ bool lastLeftState = HIGH; bool lastRightState = HIGH; bool lastRotateState = HIGH; unsigned long rotatePressTime = 0; bool softDrop = false; bool rotateHandled = false; // ============================================================ // DISPLAY COORDINATE MAPPING // ============================================================ void setPixel(int x, int y, bool state) { if (x < 0 || x >= BOARD_W || y < 0 || y >= BOARD_H) { return; } // Reverse vertical direction int physicalColumn = (BOARD_H - 1) - y; int physicalRow = x; mx.setPoint( physicalRow, physicalColumn, state ); } // ============================================================ // CLEAR DISPLAY // ============================================================ void clearDisplay() { mx.clear(); } // ============================================================ // DRAW BOARD // ============================================================ void drawBoard() { clearDisplay(); // Draw fixed blocks for (int y = 0; y < BOARD_H; y++) { for (int x = 0; x < BOARD_W; x++) { if (board[y][x]) { setPixel( x, y, true ); } } } // Draw falling piece drawCurrentPiece(); } // ============================================================ // GET ROTATED BLOCK POSITION // ============================================================ Point getRotatedPoint( Point p, int rotation ) { Point r; switch (rotation % 4) { case 0: r.x = p.x; r.y = p.y; break; case 1: r.x = -p.y; r.y = p.x; break; case 2: r.x = -p.x; r.y = -p.y; break; case 3: r.x = p.y; r.y = -p.x; break; } return r; } // ============================================================ // CHECK COLLISION // ============================================================ bool checkCollision( int pieceX, int pieceY, int rotation ) { for (int i = 0; i < 4; i++) { Point p = getRotatedPoint( pieces[currentPiece].block[i], rotation ); int x = pieceX + p.x; int y = pieceY + p.y; // Left / Right wall if (x < 0 || x >= BOARD_W) { return true; } // Bottom if (y >= BOARD_H) { return true; } // Existing block if (y >= 0 && board[y][x]) { return true; } } return false; } // ============================================================ // DRAW CURRENT PIECE // ============================================================ void drawCurrentPiece() { for (int i = 0; i < 4; i++) { Point p = getRotatedPoint( pieces[currentPiece].block[i], rotationState ); int x = currentX + p.x; int y = currentY + p.y; if (x >= 0 && x < BOARD_W && y >= 0 && y < BOARD_H) { setPixel( x, y, true ); } } } // ============================================================ // RANDOM PIECE // ============================================================ void spawnPiece() { currentPiece = random(0, 7); rotationState = 0; currentX = 3; currentY = 0; // I piece if (currentPiece == 0) { currentX = 2; } // Game over if piece cannot spawn if (checkCollision( currentX, currentY, rotationState)) { gameOver = true; if (score > highScore) { highScore = score; } soundGameOver(); } } // ============================================================ // LOCK PIECE // ============================================================ void lockPiece() { for (int i = 0; i < 4; i++) { Point p = getRotatedPoint( pieces[currentPiece].block[i], rotationState ); int x = currentX + p.x; int y = currentY + p.y; if (x >= 0 && x < BOARD_W && y >= 0 && y < BOARD_H) { board[y][x] = true; } } soundLock(); // Check completed lines clearLines(); // New piece spawnPiece(); lastFallTime = millis(); } // ============================================================ // CLEAR LINES // ============================================================ void clearLines() { int cleared = 0; for (int y = BOARD_H - 1; y >= 0; y--) { bool full = true; for (int x = 0; x < BOARD_W; x++) { if (!board[y][x]) { full = false; break; } } if (full) { cleared++; // Move rows down for (int yy = y; yy > 0; yy--) { for (int x = 0; x < BOARD_W; x++) { board[yy][x] = board[yy - 1][x]; } } // Clear top row for (int x = 0; x < BOARD_W; x++) { board[0][x] = false; } // Check same row again y++; } } // Scoring if (cleared > 0) { lines += cleared; switch (cleared) { case 1: score += 100 * level; break; case 2: score += 300 * level; break; case 3: score += 500 * level; break; case 4: score += 800 * level; break; } // Increase level every 10 lines level = (lines / 10) + 1; soundLineClear(cleared); } } // ============================================================ // MOVE LEFT // ============================================================ void moveLeft() { if (gameOver) { return; } if (!checkCollision( currentX - 1, currentY, rotationState)) { currentX--; drawBoard(); soundLeft(); } } // ============================================================ // MOVE RIGHT // ============================================================ void moveRight() { if (gameOver) { return; } if (!checkCollision( currentX + 1, currentY, rotationState)) { currentX++; drawBoard(); soundRight(); } } // ============================================================ // ROTATE // ============================================================ void rotatePiece() { if (gameOver) { return; } int newRotation = (rotationState + 1) % 4; // Normal rotation if (!checkCollision( currentX, currentY, newRotation)) { rotationState = newRotation; drawBoard(); return; } // Wall kick LEFT if (!checkCollision( currentX - 1, currentY, newRotation)) { currentX--; rotationState = newRotation; drawBoard(); return; } // Wall kick RIGHT if (!checkCollision( currentX + 1, currentY, newRotation)) { currentX++; rotationState = newRotation; drawBoard(); return; } } // ============================================================ // MOVE DOWN // ============================================================ bool moveDown() { if (gameOver) { return false; } if (!checkCollision( currentX, currentY + 1, rotationState)) { currentY++; return true; } // Cannot move further lockPiece(); return false; } // ============================================================ // SOFT DROP // ============================================================ void handleSoftDrop() { if (gameOver) { return; } static unsigned long lastSoftDrop = 0; if (millis() - lastSoftDrop >= SOFT_DROP_FALL) { lastSoftDrop = millis(); if (moveDown()) { score += 1; } drawBoard(); } } // ============================================================ // NORMAL FALL // ============================================================ void handleNormalFall() { if (gameOver) { return; } unsigned long fallSpeed; fallSpeed = NORMAL_FALL - ((level - 1) * 50); if (fallSpeed < 100) { fallSpeed = 100; } if (millis() - lastFallTime >= fallSpeed) { lastFallTime = millis(); moveDown(); drawBoard(); } } // ============================================================ // BUTTON HANDLING // ============================================================ void handleButtons() { bool leftState = digitalRead(BTN_LEFT); bool rightState = digitalRead(BTN_RIGHT); bool rotateState = digitalRead(BTN_ROTATE); // ========================================================== // LEFT // ========================================================== if (leftState == LOW && lastLeftState == HIGH) { moveLeft(); } // ========================================================== // RIGHT // ========================================================== if (rightState == LOW && lastRightState == HIGH) { moveRight(); } // ========================================================== // ROTATE BUTTON PRESSED // ========================================================== if (rotateState == LOW && lastRotateState == HIGH) { rotatePressTime = millis(); rotateHandled = false; } // ========================================================== // ROTATE BUTTON HELD // ========================================================== if (rotateState == LOW) { if (!rotateHandled && millis() - rotatePressTime >= LONG_PRESS_TIME) { rotateHandled = true; softDrop = true; } } // ========================================================== // ROTATE BUTTON RELEASED // ========================================================== if (rotateState == HIGH && lastRotateState == LOW) { unsigned long pressDuration = millis() - rotatePressTime; // Short press = ROTATE if (pressDuration < LONG_PRESS_TIME && !rotateHandled) { rotatePiece(); soundRotate(); } // Stop soft drop softDrop = false; } lastLeftState = leftState; lastRightState = rightState; lastRotateState = rotateState; } // ============================================================ // START MUSIC // ============================================================ // // Arcade-style startup melody. // // Không dùng tone liên tục. // Mỗi nốt kết thúc trước khi nốt tiếp theo bắt đầu. // ============================================================ void playStartMusic() { clearDisplay(); // ---------------------------------------------------------- // Intro LED sweep // ---------------------------------------------------------- for (int y = 0; y < BOARD_H; y++) { for (int x = 0; x < BOARD_W; x++) { setPixel( x, y, true ); } // Melody notes during sweep if (y == 0) { tone(BUZZER_PIN, 523, 100); } if (y == 4) { tone(BUZZER_PIN, 659, 100); } if (y == 8) { tone(BUZZER_PIN, 784, 100); } if (y == 12) { tone(BUZZER_PIN, 1047, 150); } if (y == 18) { tone(BUZZER_PIN, 784, 100); } if (y == 22) { tone(BUZZER_PIN, 1047, 100); } if (y == 26) { tone(BUZZER_PIN, 1319, 180); } delay(18); } delay(100); clearDisplay(); // ---------------------------------------------------------- // READY melody // ---------------------------------------------------------- tone(BUZZER_PIN, 784, 120); delay(150); tone(BUZZER_PIN, 988, 120); delay(150); tone(BUZZER_PIN, 1175, 120); delay(150); tone(BUZZER_PIN, 1568, 250); delay(300); clearDisplay(); noTone(BUZZER_PIN); } // ============================================================ // LEFT SOUND // ============================================================ void soundLeft() { tone( BUZZER_PIN, 650, 70 ); } // ============================================================ // RIGHT SOUND // ============================================================ void soundRight() { tone( BUZZER_PIN, 850, 70 ); } // ============================================================ // ROTATE SOUND // ============================================================ void soundLock() { tone(BUZZER_PIN, 450, 120); delay(130); tone(BUZZER_PIN, 300, 100); } // ============================================================ // ROTATE SOUND // ============================================================ void soundRotate() { tone( BUZZER_PIN, 1200, 100 ); } // ============================================================ // LINE CLEAR SOUND // ============================================================ void soundLineClear(int count) { if (count == 1) { tone( BUZZER_PIN, 1000, 120 ); delay(150); tone( BUZZER_PIN, 1400, 160 ); } else if (count == 2) { tone( BUZZER_PIN, 1000, 100 ); delay(120); tone( BUZZER_PIN, 1300, 100 ); delay(120); tone( BUZZER_PIN, 1700, 180 ); } else { tone( BUZZER_PIN, 1200, 100 ); delay(120); tone( BUZZER_PIN, 1500, 100 ); delay(120); tone( BUZZER_PIN, 1800, 100 ); delay(120); tone( BUZZER_PIN, 2200, 250 ); } } // ============================================================ // GAME OVER SOUND // ============================================================ void soundGameOver() { tone( BUZZER_PIN, 700, 180 ); delay(210); tone( BUZZER_PIN, 500, 180 ); delay(210); tone( BUZZER_PIN, 350, 220 ); delay(250); tone( BUZZER_PIN, 220, 450 ); delay(500); noTone(BUZZER_PIN); } // ============================================================ // GAME OVER ANIMATION // ============================================================ void gameOverAnimation() { for (int i = 0; i < 4; i++) { drawBoard(); delay(250); clearDisplay(); delay(250); } } // ============================================================ // RESET GAME // ============================================================ void resetGame() { for (int y = 0; y < BOARD_H; y++) { for (int x = 0; x < BOARD_W; x++) { board[y][x] = false; } } score = 0; lines = 0; level = 1; gameOver = false; spawnPiece(); lastFallTime = millis(); drawBoard(); } // ============================================================ // SETUP // ============================================================ void setup() { Serial.begin(115200); // Buttons pinMode( BTN_LEFT, INPUT_PULLUP ); pinMode( BTN_RIGHT, INPUT_PULLUP ); pinMode( BTN_ROTATE, INPUT_PULLUP ); // Buzzer pinMode( BUZZER_PIN, OUTPUT ); // MAX7219 mx.begin(); mx.control( MD_MAX72XX::INTENSITY, 5 ); mx.control( MD_MAX72XX::UPDATE, true ); mx.clear(); // Random seed randomSeed( analogRead(A0) ); // ========================================================== // START MUSIC // ========================================================== playStartMusic(); // ========================================================== // START GAME // ========================================================== resetGame(); gameStarted = true; } // ============================================================ // MAIN LOOP // ============================================================ void loop() { if (!gameStarted) { return; } // ========================================================== // GAME OVER // ========================================================== if (gameOver) { gameOverAnimation(); delay(500); // Restart resetGame(); return; } // ========================================================== // INPUT // ========================================================== handleButtons(); // ========================================================== // SOFT DROP // ========================================================== if (softDrop) { handleSoftDrop(); } else { handleNormalFall(); } }

Bài hướng dẫn liên quan