// int buzzer1 = 13;
// int val[8];
// int freq[]={162,294,330,350,393,441,495,990};
// void setup() {
// // put your setup code here, to run once:
// Serial.begin(115200);
// for(int i=0;i<8;i++)
// pinMode(10-i, INPUT_PULLUP);
// }
// void loop() {
// // for(int i=0;i<7;i++){
// // tone(buzzer1,freq[i],1000);
// // noTone(buzzer1);
// // delay(1000);
// // }
// for(int i=0;i<8;i++)
// {
// val[i]=digitalRead(10-i);
// delay(50);
// }
// for(int i=0;i<8;i++)
// {
// Serial.print(val[i]);
// delay(50);
// }
// Serial.println();
// }
// void sound(int pin,int duration){
// pinMode(pin,OUTPUT);
// digitalWrite(pin,HIGH);
// delay(duration);
// digitalWrite(pin,LOW);
// delay(duration);
// sound(buzzer1,1000);
// // sound(buzzer2,1000);
// }
// void tone(int pin,int freq,int duration){
// pinMode(pin,OUTPUT);
// int period=1000000/freq;
// int pulse=period/2;
// for(long i=0;i<duration*1000;i+=period){
// digitalWrite(pin,HIGH);
// delayMicroseconds(pulse);
// digitalWrite(pin,LOW);
// delayMicroseconds(pulse);
// }
// }
int buzzer1 = 13;
int val[8];
int freq[] = {162, 294, 330, 350, 393, 441, 495, 990}; // 每个 DIP 开关对应的频率
void setup() {
Serial.begin(115200);
for (int i = 0; i < 8; i++) {
pinMode(10 - i, INPUT_PULLUP); // 将 DIP 开关设置为输入
}
}
void loop() {
for (int i = 0; i < 8; i++) {
val[i] = digitalRead(10 - i); // 读取 DIP 开关状态
delay(50);
}
for (int i = 0; i < 8; i++) {
Serial.print(val[i]); // 打印 DIP 开关状态
delay(50);
}
Serial.println();
// 检查 DIP 开关状态并触发对应的声音
for (int i = 0; i < 8; i++) {
if (val[i] == LOW) { // DIP 开关开启状态(因为是 INPUT_PULLUP,所以 LOW 表示按下)
tone(buzzer1, freq[i], 500); // 播放对应开关的声音
delay(500); // 声音持续时间
}
}
}
void tone(int pin, int freq, int duration) {
pinMode(pin, OUTPUT);
int period = 1000000 / freq; // 计算声音的周期
int pulse = period / 2; // 脉冲宽度
for (long i = 0; i < duration * 1000; i += period) {
digitalWrite(pin, HIGH);
delayMicroseconds(pulse); // 持续高电平
digitalWrite(pin, LOW);
delayMicroseconds(pulse); // 持续低电平
}
}