Community project

Mario Coin Hit Sound Device

Photo of Mario Coin Hit Sound Device

Chen Henry

Published November 17, 2026

Build a Mario-style coin hit sound device that plays the iconic coin collection sound and displays a synchronized LED animation. This project uses an ESP32 microcontroller paired with a DFRobot 12-LED WS2812 ring to create a satisfying visual and audio effect triggered wirelessly via ESP-NOW.

The guide includes a complete wiring diagram for connecting the LED ring to the ESP32, a full parts list, custom firmware with MP3 audio playback and real-time LED animation sequencing, and step-by-step assembly instructions. Learn how to set up wireless triggering, synchronize audio with addressable LEDs, and optimize memory usage for high-quality sound on an embedded platform.

Wiring diagram

Wiring diagram for Mario Coin Hit Sound Device
Loading diagram…

Gather all the parts

QtyComponent
1

DFRobot DFR0888-12 WS2812 12-LED Ring

Exact DFRobot DFR0888-12 addressable RGB ring with 12 serial WS2812 LEDs, 47 mm outer diameter, 26 mm opening, 3.3-5 V supply, and PH2.0-3P IN/OUT connectors for cascading.

Assemble it in 3 steps

1. 连接12灯金币灯环

先拔掉 USB。使用灯环 IN 接口:D 接 K10 的 P0(GPIO1,灯光数据),+ 接 3V3(3.3V供电),- 接 GND(共同地线)。OUT 留空。本项目使用最高亮度金色短促爆闪,不需要外接扬声器或存储卡。

  • 请核对接口上的 D、+、- 标记,不要只按线的颜色连接。电源接反可能损坏灯环。
  • 使用3.3V供电与数据电平匹配;不要将本接线直接改成5V供电。

2. 固定与轻拍测试

将 K10 和灯环固定在轻质纸盒内,留出扬声器开口。USB供电后,启动时保持静止。按 A 或轻拍盒子时,灯环随音效进行两次金色爆闪并旋转淡出,连续触发重新闪亮。B键每按一次音量在1至10循环,屏幕显示档位;开机默认10档。

  • 爆闪不要直视,对闪光敏感者不要使用。如果最高亮度时出现重启或灯光异常,请断开USB并停止使用,不要直接改接5V。
  • 不要用头或硬物撞击,不要敲屏幕或裸露电路板。

3. ESP-NOW 无线触发测试

K10作为接收端,开机屏幕显示NOW READY、信道1和本机MAC地址(无线设备地址)。另一台控制器须使用相同信道,通过ESP-NOW向该地址发送src/coin_radio.h定义的12字节金币消息;也可用广播做初次测试。每次新触发使用不同sequence,重发同一事件保持sequence不变。无需路由器、手机联网或新增接线。原有轻拍、A键试听和B键音量功能不变。

  • 当前未加密、未绑定控制器,任何使用相同协议的附近设备都可能触发;仅用于可信环境。
  • 无线接收队列容量为32条,最快每80毫秒启动一次音效;过量消息或无线丢包不能保证每条触发。已开始的音效完整播放,连续触发时混音重叠。
  • 屏幕READY只代表无线初始化成功,不代表已经与另一台设备完成通信测试。

Review all connections

1. Connections between "ring" and "ESP32"

FunctionringESP32
digitalDATA_INGPIO 1
powerVCC3V3
groundGNDGND

Deploy the firmware

#include <Arduino.h>
#include "unihiker_k10.h"
#include <lvgl.h>
#include <math.h>
#include <WiFi.h>
#include <esp_now.h>
#include <esp_wifi.h>
#include <esp_idf_version.h>
#include "coin_radio.h"
#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel ring(12, 1, NEO_GRB + NEO_KHZ800);
uint32_t ringStart=0, ringFrame=0;
bool ringActive=false;
void updateRing(uint32_t now) {
  if(!ringActive || now-ringFrame<16) return;
  ringFrame=now;
  uint32_t age=now-ringStart;
  ring.clear();
  if(age>=960) ringActive=false;
  else {
    for(int i=0;i<12;i++) {
      int r=0,g=0,b=0;
      // Two short maximum-channel gold flashes, then a bright rotating tail.
      if(age<48 || (age>=112 && age<160)) { r=255; g=160; b=0; }
      else if(age<208) { r=0; g=0; b=0; }
      else {
        int fade=960-age;
        int head=((age-208)/35)%12;
        int distance=(i-head+12)%12;
        int brightness=distance==0?255:distance==1?128:distance==2?48:0;
        r=brightness*fade/752; g=r*160/255;
      }
      ring.setPixelColor(i,r,g,b);
    }
  }
  ring.show();
}
UNIHIKER_K10 k10;
// Reuse the exact I2S speaker configuration initialized by k10.begin().
#include <AudioGeneratorMP3.h>
#include <AudioFileSourcePROGMEM.h>
#include <AudioOutput.h>
#include "coin_mp3.h"
// Decode once into PSRAM; trim in the decoded sample domain (no MP3 frame damage).
int16_t *pcm=nullptr;
size_t pcmCount=0, trimFirst=0, trimEnd=0;
int pcmRate=48000;
bool audioReady=false;
QueueHandle_t visualQueue;
class PCMCacheOutput : public AudioOutput {
public:
  bool SetRate(int hz) override { pcmRate=hz; return AudioOutput::SetRate(hz); }
  bool begin() override { return true; }
  bool ConsumeSample(int16_t sample[2]) override {
    if(pcmCount>=120000) return false;
    pcm[pcmCount++]=(channels==1 ? sample[0] : (int32_t(sample[0])+sample[1])/2)/2;
    return true;
  }
  bool stop() override { return true; }
};
// The Wi-Fi callback only copies packets; audio and UI stay in the main loop.
struct RadioEvent { uint8_t mac[6]; CoinRadioPacket packet; };
QueueHandle_t radioQueue=nullptr;
lv_obj_t *radioLabel;
void receiveCoin(const uint8_t *mac, const uint8_t *data, int len) {
  if(!radioQueue || len!=sizeof(CoinRadioPacket)) return;
  RadioEvent event;
  memcpy(&event.packet,data,sizeof(event.packet));
  if(memcmp(event.packet.magic,"COIN",4)!=0 || event.packet.version!=1 ||
     event.packet.command!=1 || event.packet.reserved!=0) return;
  memcpy(event.mac,mac,6);
  xQueueSend(radioQueue,&event,0);
}
#if ESP_IDF_VERSION_MAJOR >= 5
void onCoinReceive(const esp_now_recv_info_t *info,const uint8_t *data,int len) {
  receiveCoin(info->src_addr,data,len);
}
#else
void onCoinReceive(const uint8_t *mac,const uint8_t *data,int len) {
  receiveCoin(mac,data,len);
}
#endif
void startRadio() {
  radioQueue=xQueueCreate(32,sizeof(RadioEvent));
  bool ok=radioQueue && WiFi.mode(WIFI_STA);
  if(ok) {
    WiFi.setSleep(false);
    ok=esp_wifi_set_channel(COIN_RADIO_CHANNEL,WIFI_SECOND_CHAN_NONE)==ESP_OK;
  }
  if(ok) ok=esp_now_init()==ESP_OK;
  if(ok) ok=esp_now_register_recv_cb(onCoinReceive)==ESP_OK;
  String mac=WiFi.macAddress();
  Serial.printf("ESP-NOW: %s, channel %u, K10 STA MAC %s\n",
                ok?"READY":"FAILED",COIN_RADIO_CHANNEL,mac.c_str());
  lv_label_set_text_fmt(radioLabel,"NOW: %s CH %u\n%s",ok?"READY":"ERROR",
                       COIN_RADIO_CHANNEL,mac.c_str());
}
lv_obj_t *countLabel, *block, *coin, *volumeLabel;
// Atomic cross-task gain: 10 preserves the existing maximum audio level.
#include <atomic>
std::atomic<int> volumeLevel{10};
bool oldB=false;
uint32_t lastVolumeChange=0;
uint32_t coins=0, lastHit=0, lastSample=0, quietSince=0, lastSampleInterval=0;
float bx=0,by=0,bz=0,gravity=1;
bool armed=true, oldA=false;
// Threshold is relative to gravity, independent of sensor output units.
// More sensitive: gentle taps rather than strong impacts.
constexpr float HIT_G=0.055f;
constexpr float QUIET_G=0.030f;
float magnitudeBaseline=1.0f, filteredMagnitude=1.0f;
float previousPulse=0;

// Up to 16 complete overlapping sounds; 80ms trigger spacing needs at most 13.
void audioTask(void*) {
  size_t positions[16]={};
  bool active[16]={};
  int16_t frames[128*2];
  xSemaphoreTake(xI2SMutex,portMAX_DELAY);
  for (;;) {
    uint32_t hits=ulTaskNotifyTake(pdTRUE,0);
    while(hits--) {
      for(int v=0;v<16;v++) if(!active[v]) {
        positions[v]=trimFirst; active[v]=true;
        uint32_t onset=millis()+(900000+pcmRate-1)/pcmRate;
        xQueueSend(visualQueue,&onset,0);
        break;
      }
    }
    const int gain=volumeLevel.load(std::memory_order_relaxed);
    for(int i=0;i<128;i++) {
      int32_t mixed=0;
      for(int v=0;v<16;v++) if(active[v]) {
        mixed+=pcm[positions[v]++];
        if(positions[v]>=trimEnd) active[v]=false;
      }
      // Saturate rather than wrap on loud overlapping transients.
      int16_t sample=constrain(mixed*gain/10,-32768,32767);
      frames[2*i]=frames[2*i+1]=sample;
    }
    size_t offset=0;
    while(offset<sizeof(frames)) {
      size_t written=0;
      i2s_write(I2S_NUM_0,reinterpret_cast<uint8_t*>(frames)+offset,
                sizeof(frames)-offset,&written,portMAX_DELAY);
      offset+=written;
    }
  }
}
TaskHandle_t soundTask=nullptr;
uint32_t animationAt=0, pendingOnset=0;
bool hasOnset=false;
void hit(uint32_t now) {
  if(!audioReady || now-lastHit<80) return;
  lastHit=now; armed=false; quietSince=0;
  xTaskNotifyGive(soundTask);
}
// One remote controller; recent sequence IDs suppress retransmissions.
// Repeat the same sequence when retrying; use a new sequence for a new hit.
void serviceRadio(uint32_t now) {
  static bool haveSender=false;
  static uint8_t sender[6];
  static uint32_t recent[64]={};
  static size_t used=0,next=0;
  if(!audioReady || now-lastHit<80) return;
  RadioEvent event;
  if(xQueueReceive(radioQueue,&event,0)!=pdTRUE) return;
  if(!haveSender || memcmp(sender,event.mac,6)!=0) {
    memcpy(sender,event.mac,6); haveSender=true; used=0; next=0;
  }
  for(size_t i=0;i<used;i++) if(recent[i]==event.packet.sequence) return;
  recent[next]=event.packet.sequence; next=(next+1)%64; used=min(size_t(64),used+1);
  hit(now);
  Serial.printf("Wireless coin: sequence %lu\n",(unsigned long)event.packet.sequence);
}
void showCoin(uint32_t now) {
  animationAt=now;
  ringStart=now; ringActive=true; ringFrame=now-16;
  updateRing(now);
  lv_label_set_text_fmt(countLabel,"COINS: %lu",(unsigned long)++coins);
  lv_obj_clear_flag(coin,LV_OBJ_FLAG_HIDDEN);
  lv_obj_set_y(block,150);
}
void setup() {
  Serial.begin(115200);
  k10.begin();
  ring.begin(); ring.setBrightness(255); ring.clear(); ring.show();
  k10.initScreen(2);
  lv_obj_set_style_bg_color(lv_scr_act(),lv_color_hex(0x142038),0);
  countLabel=lv_label_create(lv_scr_act());
  lv_obj_set_style_text_color(countLabel,lv_color_hex(0xffffff),0);
  lv_label_set_text(countLabel,"COINS: 0");
  lv_obj_align(countLabel,LV_ALIGN_TOP_MID,0,24);
  volumeLabel=lv_label_create(lv_scr_act());
  lv_obj_set_style_text_color(volumeLabel,lv_color_hex(0xffffff),0);
  lv_label_set_text(volumeLabel,"VOLUME: 10/10");
  lv_obj_align(volumeLabel,LV_ALIGN_TOP_MID,0,50);
  radioLabel=lv_label_create(lv_scr_act());
  lv_obj_set_style_text_color(radioLabel,lv_color_hex(0xffffff),0);
  lv_obj_align(radioLabel,LV_ALIGN_TOP_MID,0,73);
  lv_label_set_text(radioLabel,"NOW: starting");
  block=lv_obj_create(lv_scr_act());
  lv_obj_set_size(block,90,90); lv_obj_set_pos(block,75,160);
  lv_obj_set_style_radius(block,0,0);
  lv_obj_set_style_bg_color(block,lv_color_hex(0xf6a524),0);
  lv_obj_set_style_border_color(block,lv_color_hex(0x8f4a10),0);
  lv_obj_set_style_border_width(block,5,0);
  lv_obj_t *q=lv_label_create(block); lv_label_set_text(q,"?"); lv_obj_center(q);
  coin=lv_obj_create(lv_scr_act()); lv_obj_set_size(coin,26,38);
  lv_obj_set_pos(coin,107,105); lv_obj_set_style_radius(coin,13,0);
  lv_obj_set_style_bg_color(coin,lv_color_hex(0xffdf32),0);
  lv_obj_add_flag(coin,LV_OBJ_FLAG_HIDDEN);
  lv_obj_t *help=lv_label_create(lv_scr_act());
  lv_label_set_text(help,"Tap gently!\nA: sound test\nB: volume 1-10");
  lv_obj_set_style_text_color(help,lv_color_hex(0xffffff),0);
  lv_obj_align(help,LV_ALIGN_BOTTOM_MID,0,-15);
  // Keep still for initial gravity calibration.
  for(int i=0;i<40;i++) {
    bx+=k10.getAccelerometerX(); by+=k10.getAccelerometerY(); bz+=k10.getAccelerometerZ();
    lv_timer_handler(); delay(10);
  }
  bx/=40; by/=40; bz/=40;
  gravity=fmaxf(0.001f,sqrtf(bx*bx+by*by+bz*bz));
  magnitudeBaseline=filteredMagnitude=1.0f;
  pcm=(int16_t*)heap_caps_malloc(120000*sizeof(int16_t),MALLOC_CAP_SPIRAM|MALLOC_CAP_8BIT);
  if(pcm) {
    AudioFileSourcePROGMEM source(coinMP3,sizeof(coinMP3));
    PCMCacheOutput output;
    AudioGeneratorMP3 decoder;
    if(decoder.begin(&source,&output)) {
      while(decoder.isRunning()) {
        if(!decoder.loop()) decoder.stop();
        delay(1);
      }
    }
    int peak=0;
    for(size_t i=0;i<pcmCount;i++) peak=max(peak,abs(int(pcm[i])));
    // -60 dB relative to peak, with a 16-count floor; retain 3ms safety margins.
    int threshold=max(16,peak/1000);
    trimEnd=pcmCount;
    while(trimFirst<trimEnd && abs(int(pcm[trimFirst]))<=threshold) ++trimFirst;
    while(trimEnd>trimFirst && abs(int(pcm[trimEnd-1]))<=threshold) --trimEnd;
    size_t margin=pcmRate*3/1000;
    trimFirst=trimFirst>margin ? trimFirst-margin : 0;
    trimEnd=min(pcmCount,trimEnd+margin);
    audioReady=peak>threshold && trimEnd>trimFirst && pcmCount<120000;
    Serial.printf("Audio: %d Hz, original %u ms, cut lead %u ms, cut tail %u ms, play %u ms\n",
      pcmRate,unsigned(pcmCount*1000/pcmRate),unsigned(trimFirst*1000/pcmRate),
      unsigned((pcmCount-trimEnd)*1000/pcmRate),unsigned((trimEnd-trimFirst)*1000/pcmRate));
  }
  visualQueue=xQueueCreate(16,sizeof(uint32_t));
  if(audioReady && visualQueue) {
    i2s_set_sample_rates(I2S_NUM_0,pcmRate);
    i2s_zero_dma_buffer(I2S_NUM_0);
    xTaskCreate(audioTask,"coinAudio",4096,nullptr,2,&soundTask);
  } else { audioReady=false; lv_label_set_text(countLabel,"Audio load failed"); }
  startRadio();
  lastHit=millis();
  lastSampleInterval=lastHit;
}
void loop() {
  uint32_t now=millis();
  lv_timer_handler();
  if(radioQueue) serviceRadio(now);
  bool a=k10.buttonA->isPressed();
  if(a&&!oldA) hit(now);
  oldA=a;
  bool b=k10.buttonB->isPressed();
  if(b && !oldB && now-lastVolumeChange>=180) {
    int level=volumeLevel.load(std::memory_order_relaxed)%10+1;
    volumeLevel.store(level,std::memory_order_relaxed);
    lv_label_set_text_fmt(volumeLabel,"VOLUME: %d/10",level);
    lastVolumeChange=now;
  }
  oldB=b;
  if(now-lastSample>=5) {
    lastSample=now;
    float x=k10.getAccelerometerX(),y=k10.getAccelerometerY(),z=k10.getAccelerometerZ();
    // The vector length is independent of board orientation: tilting changes
    // X/Y/Z but not the length of gravity. Do not detect vector direction.
    float magnitude=sqrtf(x*x+y*y+z*z)/gravity;
    float dt=constrain(float(now-lastSampleInterval)/1000.0f,0.003f,0.030f);
    lastSampleInterval=now;
    // ~3ms low-pass removes very short electrical noise; ~90ms baseline
    // removes slow handling. Time-based coefficients tolerate display work.
    filteredMagnitude+=(dt/(0.003f+dt))*(magnitude-filteredMagnitude);
    magnitudeBaseline+=(dt/(0.090f+dt))*(filteredMagnitude-magnitudeBaseline);
    float pulse=filteredMagnitude-magnitudeBaseline;
    float impact=fabsf(pulse);
    float slew=fabsf(pulse-previousPulse)/dt;
    previousPulse=pulse;
    // Detect the onset, not a mandatory release within a narrow time window.
    // Magnitude rejects pure rotation; high-pass rejects slow handling.
    // A gentle short pulse qualifies without needing a hard collision.
    if(armed && impact>HIT_G && slew>1.5f && now-lastHit>=80) {
      hit(now);
    }
    // Hysteresis prevents one ringing impact from counting repeatedly.
    // Rearm after 15ms near baseline, retaining fast consecutive taps.
    if(impact<QUIET_G) {
      if(!quietSince) quietSince=now;
      if(now-quietSince>=15 && now-lastHit>=80) armed=true;
    } else quietSince=0;
  }
  if(!hasOnset) hasOnset=xQueueReceive(visualQueue,&pendingOnset,0)==pdTRUE;
  if(hasOnset && int32_t(now-pendingOnset)>=0) { showCoin(now); hasOnset=false; }
  if(now-animationAt>160 && !lv_obj_has_flag(coin,LV_OBJ_FLAG_HIDDEN)) {
    lv_obj_add_flag(coin,LV_OBJ_FLAG_HIDDEN); lv_obj_set_y(block,160);
  }
  updateRing(millis());
  delay(2);
}

Download project files

Remix this project

Make it yours in one click

Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.

Open in Schematik