以下是一个简单的 Arduino 触摸钢琴代码示例,教你如何使用 Arduino 和触摸传感器构建一个音乐触控板。

#include <CapacitiveSensor.h>

// 定义触摸钢琴的引脚
const int numPins = 8; // 钢琴键的数量
const int sendPin = 9; // 发送引脚
const int receivePin = 10; // 接收引脚
CapacitiveSensor cs = CapacitiveSensor(sendPin, receivePin); // 创建一个触摸传感器对象

// 定义每个钢琴键的频率
const int freqs[] = {262, 294, 330, 349, 392, 440, 494, 523};

// 定义每个钢琴键的电容阈值
const int thresholds[] = {600, 600, 600, 600, 600, 600, 600, 600};

void setup() {
  Serial.begin(9600);
}

void loop() {
  for (int i = 0; i < numPins; i++) {
    long touchValue = cs.capacitiveSensor(30); // 读取触摸传感器的值

    if (touchValue > thresholds[i]) { // 如果触摸值超过阈值
      playSound(freqs[i]); // 播放音符
      delay(100); // 延迟一段时间,避免重复触发
    }
  }
}

// 播放指定频率的音符
void playSound(int freq) {
  tone(8, freq); // 发出音符
  delay(200); // 持续一段时间
  noTone(8); // 停止发出音符
}

请注意,这只是一个基本的示例代码,你可能需要根据你的具体硬件和需求进行调整。另外,你需要安装并导入 CapacitiveSensor 库,以便使用触摸传感器功能。

Arduino 触摸钢琴代码示例:打造你的音乐触控板

原文地址: http://www.cveoy.top/t/topic/psJR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录