Keyboard Sound Effects

Hi everyone! I am trying to make many sound effects for a small keyboard or piano, and I am running into trouble.

I have already made a code for a trumpet effect, but I want to make some others and I just cant get them right.

If someone could help me modify the trumpet code to make a new one, that would be great. Thank you! Here is the code:

/* PWM Melody via DCB...Trumpet effect*/

//pin 10 pwm sound with pitch and volume control
#define piezoPin 10 
#define minVol 1
#define maxVol 128 

void setup(){
  pinMode(piezoPin,OUTPUT);
  pinMode(9,OUTPUT);
  TCCR1A = (1 << COM1A1) | (1 << COM1B1 | 1 << WGM10);// sets timer control bits to PWM Phase and Frequency Correct mode
  TCCR1B = 0x12; // sets timer control bits to Prescaler N = 8
  analogWrite(piezoPin, 127); //something less than full volume
}

int length = 15; // the number of notes
char notes[] = "fffffffffffffff "; // type in any notes to a song
int beats[] = { 1, 1, 2, 1, 1, 2, 1, 1, 1, 2, 1, 4 };
int tempo = 450;

void playNote(char note, int duration) {
  char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', ' ' };
  int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 958, 30 };
  int d = duration;
  // play the tone corresponding to the note name
  for (int i = 0; i < 9; i++) {
    if (names[i] == note) {
      OCR1A=tones[i];
      
      //attack
      for(int x = minVol; x < maxVol;x*=2){ 
        analogWrite(piezoPin, note == ' '?minVol:x);
        delay(10);
        d-=10;
      }

      //decay
      int x = maxVol;      
      while(d >= 2){
        analogWrite(piezoPin, note == ' '?minVol:x);
        x-=1;
        if(x<minVol) x = minVol;
        delay(5);
        d-=5;
      }
      
      analogWrite(piezoPin, minVol);
      delay(2);
    }
  }
}


void loop() {
  for (int i = 0; i < length; i++) {
     playNote(notes[i], beats[i] * tempo);
  }
}

Hi,
You should try a more complex synth engine, this one has four voices with independent envelopes, that will give you everything from a snare drum to a flute.

If you check the RCArduino video channel over the next few days I will publish a full demonstration video of my own 5 dollar keyboard project -

This has a less complicated engine but still makes some big sounds.

Duane B

Thank you very much DuaneB, I will definitely use this :slight_smile: