2012年4月19日 星期四

HW10_02: Speaker


// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int buttonPin1 = 3;
const int buttonPin2 = 4;
const int buttonPin3 = 5;
int speakerOut = 9;
// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;

void setup() {
  pinMode(speakerOut, OUTPUT);  
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);  
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);
  buttonState3 = digitalRead(buttonPin3);
  /*
   #define c 3830 // 261 Hz
   #define d 3400 // 294 Hz
   #define e 3038 // 329 Hz
   #define f 2864 // 349 Hz
   #define g 2550 // 392 Hz
   #define a 2272 // 440 Hz
   #define b 2028 // 493 Hz
   #define C 1912 // 523 Hz
   */
  int tone_0 = 3830;
  int tone_1 = 3400;
  int tone_2 = 3038;
  int tone_3 = 2864;
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {  
    digitalWrite(speakerOut,HIGH);
    delayMicroseconds(tone_0 /2);
    digitalWrite(speakerOut, LOW);
    delayMicroseconds(tone_0 /2);
  } /*
  else {
    digitalWrite(speakerOut, LOW);
    delayMicroseconds(tone_0 /2);
  }*/

  if (buttonState1 == HIGH) {  
    digitalWrite(speakerOut,HIGH);
    delayMicroseconds(tone_1 /2);
    digitalWrite(speakerOut, LOW);
    delayMicroseconds(tone_1 /2);
  }/*
  else {
    digitalWrite(speakerOut, LOW);
    delayMicroseconds(tone_1 /2);
  }*/

  if (buttonState2 == HIGH) {  
    digitalWrite(speakerOut,HIGH);
    delayMicroseconds(tone_2 /2);
    digitalWrite(speakerOut, LOW);
    delayMicroseconds(tone_2 /2);
  } /*
  else {
    digitalWrite(speakerOut, LOW);
    delayMicroseconds(tone_2 /2);
  }*/

  if (buttonState3 == HIGH) {  
    digitalWrite(speakerOut,HIGH);
    delayMicroseconds(tone_3 /2);
    digitalWrite(speakerOut, LOW);
    delayMicroseconds(tone_3 /2);
  } /*
  else {
    digitalWrite(speakerOut, LOW);
    delayMicroseconds(tone_3 /2);
  }*/
}

沒有留言:

張貼留言