Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This is a simple test sketch to see if your DF Player works and see what checksum it uses
- #include <SoftwareSerial.h>
- #define TX_PIN 9
- #define RX_PIN 8
- const size_t RX_PACKET_SIZE = 10;
- const uint8_t startByte = 0x7E, ver = 0xFF, len = 0x06, endByte = 0xEF;
- int rxBuffer[RX_PACKET_SIZE], rxIndex = 0;
- SoftwareSerial dfSerial(RX_PIN, TX_PIN); // (RX, TX) pins
- void sendPacket(byte cmd, byte feedBack, byte folder, byte file){
- uint8_t txBuffer[]{startByte, ver, len, cmd, feedBack, folder, file, endByte};
- Serial.print("Setting bytes :");
- for(byte i = 0; i < 8; i++){
- dfSerial.write(txBuffer[i]);
- Serial.print("0x");
- Serial.print(txBuffer[i], HEX);
- Serial.print(" ");
- delay(10);
- }
- Serial.println("\n");
- }
- void setup() {
- // Initialize serial communication at 115200 baud
- Serial.begin(115200);
- while (!Serial) {;}
- Serial.println("Setting up DFPlayer Serial Connection\n");
- dfSerial.begin(9600);
- delay(1000);
- while (!dfSerial) {;}
- Serial.println("DFPlayer Serial Up\n");
- sendPacket(0x0C, 0, 0, 0); //This is the reset command
- delay(500);
- sendPacket(0x09, 0, 0, 2); //This set the source to the TF card = 2, USB = 1
- delay(500);
- sendPacket(0x06, 0, 0, 25); //This sets the Volume (0 - 30)
- delay(500);
- sendPacket(0x03, 1, 0, 1); //This plays file 001.mp3 in the root of the SD card and will reply to confirm
- }
- void loop() {
- while (dfSerial.available() > 0) {
- uint8_t incomingByte = dfSerial.read();
- // STEP 1: If we are not actively tracking a packet, wait until we see 0x7E
- if (rxIndex == 0) {
- if (incomingByte == startByte) {
- rxBuffer[0] = incomingByte;
- rxIndex = 1; // Move to the next slot for the next byte
- }
- // If it's not 0x7E, we do nothing and let the loop check the next byte
- }
- // STEP 2: We are actively collecting the packet
- else if (rxIndex < RX_PACKET_SIZE) {
- rxBuffer[rxIndex] = incomingByte;
- // STEP 3: If we just grabbed the last byte (index 9), validate the marker
- if (rxIndex == RX_PACKET_SIZE -1) {
- if (rxBuffer[RX_PACKET_SIZE - 1] == endByte) {
- // Success! Valid 10-byte frame found.
- for(byte i = 0; i < RX_PACKET_SIZE; i++){
- Serial.print("0x");
- Serial.print(rxBuffer[i], HEX);
- Serial.print(" ");
- }
- Serial.println("\n");
- } else {
- // Error: The 10th byte wasn't 0xEF. Frame is corrupt.
- // Optional: handle error here
- Serial.println("Data receive ERROR\n");
- }
- // Reset the index so we start looking for a new 0x7E on subsequent bytes
- rxIndex = 0;
- } else {
- rxIndex++;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment